用 QT 实现一个主界面,主界面中包含 7 个图标按钮,长按图标按钮实现图标按钮随鼠标移动,双击按钮能进入其他界面。同时为主界面和图标按钮都设置背景图片。用代码实现以上要求并将.h和.cpp文件分开
时间: 2024-04-16 09:26:55 浏览: 103
下面是使用QT实现主界面的示例代码将代码分为.h和.cpp文件。
MainWindow.h:
```cpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
#include <QGridLayout>
#include <QTimer>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void onButtonPressed();
void onButtonReleased();
void onButtonMouseMove();
void onButtonDoubleClicked();
private:
void setupUI();
void setBackground();
void createButtons();
QWidget *centralWidget;
QGridLayout *gridLayout;
QTimer *longPressTimer;
QPoint lastMousePos;
};
#endif // MAINWINDOW_H
```
MainWindow.cpp:
```cpp
#include "mainwindow.h"
#include <QPalette>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
setupUI();
setBackground();
createButtons();
longPressTimer = new QTimer(this);
longPressTimer->setInterval(1000);
connect(longPressTimer, &QTimer::timeout, this, &MainWindow::onButtonMouseMove);
}
MainWindow::~MainWindow()
{
}
void MainWindow::setupUI()
{
centralWidget = new QWidget(this);
gridLayout = new QGridLayout(centralWidget);
setCentralWidget(centralWidget);
}
void MainWindow::setBackground()
{
QPalette palette;
palette.setBrush(this->backgroundRole(), QBrush(QImage("background.jpg")));
this->setPalette(palette);
}
void MainWindow::createButtons()
{
for (int i = 0; i < 7; i++) {
QPushButton *button = new QPushButton(centralWidget);
button->setIcon(QIcon("icon.png"));
button->setIconSize(QSize(100, 100));
button->setStyleSheet("background-color: transparent; border: none;");
gridLayout->addWidget(button, i / 3, i % 3);
connect(button, &QPushButton::pressed, this, &MainWindow::onButtonPressed);
connect(button, &QPushButton::released, this, &MainWindow::onButtonReleased);
connect(button, &QPushButton::doubleClicked, this, &MainWindow::onButtonDoubleClicked);
}
}
void MainWindow::onButtonPressed()
{
QPushButton *button = qobject_cast<QPushButton*>(sender());
lastMousePos = button->mapToGlobal(QPoint(0, 0));
longPressTimer->start();
}
void MainWindow::onButtonReleased()
{
longPressTimer->stop();
}
void MainWindow::onButtonMouseMove()
{
QPushButton *button = qobject_cast<QPushButton*>(sender());
if (longPressTimer->isActive()) {
QPoint currentMousePos = QCursor::pos();
int dx = currentMousePos.x() - lastMousePos.x();
int dy = currentMousePos.y() - lastMousePos.y();
int newX = button->x() + dx;
int newY = button->y() + dy;
button->move(newX, newY);
lastMousePos = currentMousePos;
}
}
void MainWindow::onButtonDoubleClicked()
{
// 进入其他界面的逻辑处理
}
```
请确保在.h文件中包含所需的头文件,并在.cpp文件中实现相应的函数。同时,将"background.jpg"和"icon.png"替换为您自己的图片路径。希望对您有所帮助!如果还有其他问题,请随时提问。
阅读全文