滑鼠事件(QMouseEvent)

這邊示範滑鼠事件的使用,用繼承自QWidget的自定義Widget元件,重載QWidget原本的QMouseEvent函式,使得滑鼠在點擊、移動、雙點擊及釋放時,此時相對的QLabel上會顯示滑鼠位置。


widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QLabel>
#include <QVBoxLayout>
#include <QMouseEvent>

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    void mouseMoveEvent(QMouseEvent *event);
    void mousePressEvent(QMouseEvent *event);
    void mouseDoubleClickEvent(QMouseEvent *event);
    void mouseReleaseEvent(QMouseEvent *event);
private:
    QLabel *moveLabel;
    QLabel *pressLabel;
    QLabel *doubleClickLabel;
    QLabel *releaseLabel;
    QVBoxLayout *mainLayout;
};

#endif 

widget.cpp

#include "widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent)
{
    setWindowTitle(tr("滑鼠事件"));
    moveLabel = new QLabel(this);
    pressLabel = new QLabel(this);
    doubleClickLabel = new QLabel(this);
    releaseLabel = new QLabel(this);

    moveLabel->setText(tr(""));
    pressLabel->setText(tr(""));
    doubleClickLabel->setText(tr(""));
    releaseLabel->setText(tr(""));

    moveLabel->setAlignment(Qt::AlignCenter);  //label文字置中
    pressLabel->setAlignment(Qt::AlignCenter);
    doubleClickLabel->setAlignment(Qt::AlignCenter);
    releaseLabel->setAlignment(Qt::AlignCenter);

    mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(moveLabel);
    mainLayout->addWidget(pressLabel);
    mainLayout->addWidget(doubleClickLabel);
    mainLayout->addWidget(releaseLabel);

    //預設為false,此時要按著滑鼠才會追蹤位置,如果mouseTracking為true,則只要滑鼠在視窗範圍內就會追蹤位置
    setMouseTracking(true);
}

void Widget::mouseMoveEvent(QMouseEvent *event){
    //arg()函數可以替換掉QString中出現的佔位符。占位符為%加位置,如%1、%2。
    moveLabel->setText(QString(tr("移動到:(%1, %2)")).arg(QString::number(event->x()), QString::number(event->y())));
}

void Widget::mousePressEvent(QMouseEvent *event){
    pressLabel->setText(QString(tr("點擊處:(%1, %2)")).arg(QString::number(event->x()), QString::number(event->y())));
}

void Widget::mouseDoubleClickEvent(QMouseEvent *event){
    doubleClickLabel->setText(QString(tr("雙擊處:(%1, %2)")).arg(QString::number(event->x()), QString::number(event->y())));
}

void Widget::mouseReleaseEvent(QMouseEvent *event){
    releaseLabel->setText(QString(tr("釋放處:(%1, %2)")).arg(QString::number(event->x()), QString::number(event->y())));
}

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.resize(200,200);
    w.show();

   return a.exec();
}

QMouseEvent