Qt5鼠標事件及實例


mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QLabel>
#include <QStatusBar>
#include <QMouseEvent>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
protected:
    //重定義了QWidget類的鼠標事件方法
    void mousePressEvent(QMouseEvent *e);
    void mouseMoveEvent(QMouseEvent *e);
    void mouseReleaseEvent(QMouseEvent *e);
    void mouseDoubleClickEvent(QMouseEvent *e);
private:
    QLabel *statusLabel;
    QLabel *MousePosLabel;

};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setWindowTitle(tr("鼠標事件"));
    statusLabel=new QLabel;
    statusLabel->setText(tr("當前位置:"));
    statusLabel->setFixedWidth(100);
    MousePosLabel=new QLabel;
    MousePosLabel->setText(tr(""));
    MousePosLabel->setFixedWidth(100);

    //在QMainWindow的狀態欄中加入控件
    statusBar()->addPermanentWidget(statusLabel);
    statusBar()->addPermanentWidget(MousePosLabel);
    //設置窗體追蹤鼠標
    this->setMouseTracking(true);
    resize(400,200);
}
//mousePressEvent()函數為鼠標按下事件響應函數
void MainWindow::mousePressEvent(QMouseEvent *e)
{
    if(e->button() == Qt::LeftButton)
    {
        statusBar()->showMessage(tr("左鍵"));
    }
    else if(e->button() == Qt::RightButton)
    {
        statusBar()->showMessage(tr("右鍵"));
    }
    else if(e->button() == Qt::MidButton)
    {
        statusBar()->showMessage(tr("中鍵"));
    }
}
//mouseMoveEvent()函數為鼠標移動事件響應函數
void MainWindow::mouseMoveEvent(QMouseEvent *e)
{
    MousePosLabel->setText("("+QString::number(e->x())+","+QString::number(e->y())+")");
}
//mouseReleaseEvent()函數為鼠標松開事件響應函數
void MainWindow::mouseReleaseEvent(QMouseEvent *e)
{

}
//mouseDoubleClickEvent()函數為鼠標雙擊事件響應函數
void MainWindow::mouseDoubleClickEvent(QMouseEvent *e)
{

}
MainWindow::~MainWindow()
{

}

main.cpp

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

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

    return a.exec();
}

運行效果

鼠標移動時,顯示鼠標的坐標


當鼠標左鍵按下時,顯示左鍵按下

參考資料
《Qt5開發及實例》


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM