天天看點

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.9.0之滑鼠點選事件

此例子我在一本QT5 開發及執行個體中看到的,陸文周主編,建議大家去看看。 

Qt

繼續閱讀