修改QLabel使QLabel支持鼠标事件
分类:Others, Qt
阅读 (2,779)
Add comments
1月 272019
QLabel并不支持鼠标按下、松开等事件,我们需要新建一个QLabel的子类来支持。
编写qadvancedlabel.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#ifndef QADVANCEDLABEL_H #define QADVANCEDLABEL_H #include <QLabel> class QAdvancedLabel : public QLabel { Q_OBJECT public: QAdvancedLabel(QWidget *parent = nullptr); protected: virtual void mousePressEvent(QMouseEvent *event); //鼠标按下 virtual void mouseReleaseEvent(QMouseEvent *event); //鼠标松开 virtual void mouseDoubleClickEvent(QMouseEvent *event); //双击鼠标 virtual void mouseMoveEvent(QMouseEvent *event); //鼠标移动 signals: void pressed(QMouseEvent *event); //鼠标按下 void clicked(QMouseEvent *event); //鼠标松开 void doubled(QMouseEvent *event); //双击鼠标 void moved(QMouseEvent *event); //鼠标移动 public slots: }; #endif // QADVANCEDLABEL_H |
然后增加QAdvancedLabel的cpp文件,qadvancedlabel.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include "include/qadvancedlabel.h" QAdvancedLabel::QAdvancedLabel(QWidget *parent) : QLabel(parent) { } void QAdvancedLabel::mousePressEvent(QMouseEvent *event) { emit pressed(event); } void QAdvancedLabel::mouseReleaseEvent(QMouseEvent *event) { emit clicked(event); } void QAdvancedLabel::mouseDoubleClickEvent(QMouseEvent *event) { emit doubled(event); } void QAdvancedLabel::mouseMoveEvent(QMouseEvent *event) { emit moved(event); } |
然后在程序中的实现:
mainwindow.h文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QObject> #include <QMainWindow> #include <QMouseEvent> #include "qadvancedlabel.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void onQAdvLabelMouseEvent(QMouseEvent *event); private: Ui::MainWindow *ui; QAdvancedLabel *testQAdvLabel; }; #endif // MAINWINDOW_H |
mainwindow.cpp文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); testQAdvLabel = new QAdvancedLabel(ui->centralWidget); testQAdvLabel->setText("test mouse move"); connect(testQAdvLabel, SIGNAL(moved(QMouseEvent*)), this, SLOT(onQAdvLabelMouseEvent(QMouseEvent*))); testQAdvLabel->setMouseTracking(true); } void MainWindow::onQAdvLabelMouseEvent(QMouseEvent *event) { qDebug("x: %d, y: %d", event->x(), event->y()); } |
记得一定要设置setMouseTracking,否则只有按下时才会响应move事件。