Qt 使用mouseMoveEvent信号跟踪鼠标移动


使用前,先#include <QMouseEvent>

在MainWindow类中重写mouseMoveEvent函数,并自定义一个信号(这里是mouseMove)

 1 //mainwindow.h
 2  
 3 #ifndef MAINWINDOW_H  4 #define MAINWINDOW_H
 5  
 6 #include <QMainWindow>
 7 #include <QWidget>
 8 #include <QMouseEvent>
 9  
10 namespace Ui { 11 class MainWindow; 12 } 13  
14 class MainWindow : public QMainWindow 15 { 16  Q_OBJECT 17  
18 public: 19     explicit MainWindow(QWidget *parent = nullptr); 20     ~MainWindow(); 21  
22 private: 23     Ui::MainWindow *ui; 24     void mouseMoveEvent(QMouseEvent *event);//重写mouseMoveEvent函数
25  
26 private slots: 27     void draw(QMouseEvent *event);//这是跟踪鼠标移动要触发的槽函数
28  
29 signals: 30     void mouseMove(QMouseEvent *event);//自定义一个信号
31 };

重写mouseMoveEvent函数,内容为发送mouseMove信号即可

 1 //mainwindow.cpp
 2  
 3 #include "mainwindow.h"
 4 #include "ui_mainwindow.h"
 5  
 6 MainWindow::MainWindow(QWidget *parent) :  7  QMainWindow(parent),  8     ui(new Ui::MainWindow)  9 { 10     ui->setupUi(this); 11  
12     connect(this,SIGNAL(mouseMove(QMouseEvent *)),this,SLOT(draw(QMouseEvent *))); 13  
14     QMainWindow::setMouseTracking(true); 15     QMainWindow::centralWidget()->setMouseTracking(true); 16     ui->openGLWidget->setMouseTracking(true); 17 } 18  
19 MainWindow::~MainWindow() 20 { 21     delete ui; 22 } 23  
24 void MainWindow::draw(QMouseEvent *event){ 25  pass 26 } 27  
28 void MainWindow::mouseMoveEvent(QMouseEvent *event){ 29     emit mouseMove(event); 30 }

 

需要注意的是,在MainWindow构造函数中对需要跟踪鼠标位置的组件,及其所属的各级父类和容器setMouseTracking(true),否则只有在按住左键或右键时才会捕捉鼠标位置。

网上很多setMouseTracking(true)了没起作用的,是因为只调用了一次,没有对父类和容器调用


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM