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