最近在学习点击鼠标事件,在这分享给大家
window.h中的配置
#ifndef MAINWINDOW_H#define MAINWINDOW_H#include <QMainWindow>#include"Qlabel"#include"QStatusBar"#include <QMainWindow>#include"QMouseEvent"namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = 0);~MainWindow();protected:void mousePressEvent(QMouseEvent *e);//鼠标点击事件void mouseMoveEvent(QMouseEvent *e);//鼠标移动事件void mouseReleaseEvent(QMouseEvent *e);//鼠标释放事件void mouseDoubleClickEvent(QMouseEvent *e);//鼠标双击事件private:Ui::MainWindow *ui;QLabel *statusLabel; //控件 QLabelQLabel *MousePosLabel;//控件 QLabel};#endif // MAINWINDOW_H
mainwindow.cpp中配置
#include "mainwindow.h"#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent)// ui(new Ui::MainWindow){// ui->setupUi(this);setWindowTitle(tr("鼠标事件"));statusLabel=new QLabel; //创建控件 LABELstatusLabel->setText(tr("当前位置:"));//statusLabel->SetFixedXY(40,40);statusLabel->setFixedWidth(100); //设置控件宽度 SetFixedXY SetFixedHeight SetFixedWidthMousePosLabel=new QLabel;MousePosLabel->setText(tr(""));MousePosLabel->setFixedWidth(100);statusBar()->addPermanentWidget(statusLabel);//在状态栏中增加控件statusBar()->addPermanentWidget(MousePosLabel);//在状态栏中增加控件this->setMouseTracking(true);//设置窗体追踪鼠标resize(1366,768);//设置窗口大小}MainWindow::~MainWindow(){delete ui;}void MainWindow::mousePressEvent(QMouseEvent *e){QString str="("+QString::number(e->x())+","+QString::number(e->y())+")";if(e->button()==Qt::LeftButton){//左键按下 显示按下坐标statusBar()->showMessage(tr("左键:")+str);}if(e->button()==Qt::RightButton){//右键按下 显示按下坐标statusBar()->showMessage(tr("右键:")+str);}else if(e->button()==Qt::MidButton){//中键按下 显示按下坐标statusBar()->showMessage(tr("中键:")+str);}}void MainWindow::mouseMoveEvent(QMouseEvent *e){//鼠标移动追踪事件 显示按下坐标MousePosLabel->setText("("+QString::number(e->x())+","+QString::number(e->y())+")");}void MainWindow::mouseReleaseEvent(QMouseEvent *e){//鼠标释放追钟事件QString str="("+QString::number(e->x())+","+QString::number(e->y())+")";statusBar()->showMessage(tr("释放在:")+str,3000);}//鼠标双击事件void MainWindow::mouseDoubleClickEvent(QMouseEvent *e){QString str="("+QString::number(e->x())+","+QString::number(e->y())+")";statusBar()->showMessage(tr("双击在:")+str,3000);}
main.cpp中配置
#include "mainwindow.h"#include <QApplication>//#include"mouseevent.h"int main(int argc, char *argv[]){QApplication a(argc, argv);MainWindow w;w.show();return a.exec();}
运行后结果
此例子我在一本QT5 开发及实例中看到的,陆文周主编,建议大家去看看。