文章目录
前言
在QT项目中有的时候,我们需要自定义标题栏,但是自定义的标题栏要想和系统的标题栏一样可以移动窗口,就需要我们重载实现鼠标的点击,移动,释放,三个鼠标事件来实现窗口的移动
一、鼠标事件
void mouseMoveEvent(QMouseEvent *event);//鼠标移动 void mousePressEvent(QMouseEvent *event);//鼠标点击 void mouseReleaseEvent(QMouseEvent *event);//鼠标释放
二、.代码
1..h文件
代码如下(示例):
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QMouseEvent> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); protected: void mouseMoveEvent(QMouseEvent *event);//鼠标移动 void mousePressEvent(QMouseEvent *event);//鼠标点击 void mouseReleaseEvent(QMouseEvent *event);//鼠标释放 bool _switch = false;//bool标识用来标记鼠标点击的位置是否正确 QPoint _click;//记录鼠标按下时的起始位置 private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
2..cpp文件
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
//鼠标按下 void MainWindow::mousePressEvent(QMouseEvent *event) { //我这里只进行了简单的判断 //如果需要特定区域点击才能移动的话 //可以对xy轴进行判断 event->pos()返回的坐标是UI中的坐标不是屏幕坐标, //x轴小于50,y轴小于100的位置点击才能通过判断,大家可以进行多种判断来做到点击指定区域才能移动 if(event->pos().x() > 50 && event->pos().y() > 100){ return; } //判断是否是左键点击,注意如果在按钮上点击,点击事件会被按钮截获,所以按钮上的点击事件不会到达这里, //但是当鼠标移动出按钮区域,移动事件会被截获所以需要有标识标记点击的起始位置是不是我们想要的 if (event->button() == Qt::LeftButton){ _switch = true;//点击区域正确标识为真 _click = event->pos();//记录鼠标按下的位置用于计算移动量 } } //鼠标移动 void MainWindow::mouseMoveEvent(QMouseEvent *event) { //判断标识,只要有一个为假则不进行移动。第一个,左键按下才移动,第二个必须在指定区域按下并且不能为按钮 if ((!event->buttons().testFlag(Qt::LeftButton))|| (!_switch)) return; //计算xy坐标移动量是多少 int dx = event->pos().x() - _click.x(); int dy = event->pos().y() - _click.y(); //将窗口移动到指定位置 this->move(this->x()+dx,this->y()+dy); } //鼠标释放 void MainWindow::mouseReleaseEvent(QMouseEvent *event) { //鼠标释放后标识要重置 _switch = false; }
总结
注意有的时候明明有移动事件存在,但是重载时event报错灰色加入头文件#include <QMouseEvent>即可解决,这里只是简单的点击移动,希望这篇文章对大家有帮助。