zoukankan      html  css  js  c++  java
  • 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开发及实例》

  • 相关阅读:
    团队编程项目作业3-模块测试过程
    团队编程项目作业3-模块开发过程
    课后作业-结队编程项目进度
    团队编程项目作业2-团队编程项目代码设计规范
    课后作业-阅读任务-阅读提问-1
    团队-爬取豆瓣电影Top250-项目总结
    团队-爬取豆瓣Top250-最终程序
    课后作业-阅读任务-阅读提问-4
    《20171129-构建之法:现代软件工程-阅读笔记》
    《软件工程课程总结》
  • 原文地址:https://www.cnblogs.com/Manual-Linux/p/9567430.html
Copyright © 2011-2022 走看看