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开发及实例》

  • 相关阅读:
    UML类图基础说明
    grep: /usr/include/php/main/php.h: No such file or directory
    活在幻梦中的你我
    Markdown语法笔记
    眼见为实
    潜意识与暗示
    蝌蚪与青蛙是同一个物种么?
    PHP 数组函数整理
    git 笔记
    vue2.0-组件传值
  • 原文地址:https://www.cnblogs.com/Manual-Linux/p/9567430.html
Copyright © 2011-2022 走看看