QT5.9.0之鼠标点击事件

最近在学习点击鼠标事件,在这分享给大家

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_OBJECT

public:
    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;  //控件  QLabel
    QLabel *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; //创建控件  LABEL
    statusLabel->setText(tr("当前位置:"));
    //statusLabel->SetFixedXY(40,40);
    statusLabel->setFixedWidth(100);  //设置控件宽度  SetFixedXY   SetFixedHeight    SetFixedWidth
    MousePosLabel=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 开发及实例中看到的,陆文周主编,建议大家去看看。 

猜你喜欢

转载自blog.csdn.net/weixin_41331879/article/details/81587418