QMouseEvent
生活随笔
收集整理的這篇文章主要介紹了
QMouseEvent
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1 QMouseEvent
- 1.1 特別說明
- 2 通過QMouseEvent事件實現窗口移動
1 QMouseEvent
1.1 特別說明
QMouseEvent沒啥要注意的,就是對于mouseMoveEvent,默認情況下,觸發事件需要點擊一下,才能觸發。可設置為自動觸發:setMouseTracking(true);。
2 通過QMouseEvent事件實現窗口移動
實現起來還是比較簡單的。
頭文件:
#ifndef WIDGET_H #define WIDGET_H#include <QWidget>namespace Ui { class Widget; }class Widget : public QWidget {Q_OBJECTpublic:explicit Widget(QWidget *parent = nullptr);~Widget();private:Ui::Widget *ui;protected://拖拽窗口,重寫三個虛函數void mousePressEvent(QMouseEvent *event);void mouseMoveEvent(QMouseEvent *event);void mouseReleaseEvent(QMouseEvent *event);private:bool m_bDrag;QPoint mouseStartPoint;QPoint windowTopLeftPoint; };#endif // WIDGET_H實現文件:
#include "widget.h" #include "ui_widget.h" #include <QMouseEvent>Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget),m_bDrag(false) {ui->setupUi(this);setWindowTitle("窗口拖拽移動");setFixedSize(640, 480);}Widget::~Widget() {delete ui; }//拖拽操作 void Widget::mousePressEvent(QMouseEvent *event) {if(event->button() == Qt::LeftButton){m_bDrag = true;//獲得鼠標的初始位置mouseStartPoint = event->globalPos();//mouseStartPoint = event->pos();//獲得窗口的初始位置windowTopLeftPoint = this->frameGeometry().topLeft();} }void Widget::mouseMoveEvent(QMouseEvent *event) {if(m_bDrag) {//獲得鼠標移動的距離//QPoint distance = event->pos() - mouseStartPoint;QPoint distance = event->globalPos() - mouseStartPoint;//改變窗口的位置this->move(windowTopLeftPoint + distance);/*注意:一般定位鼠標坐標使用的是event->pos()和event->globalPos()兩個函數,event->pos()鼠標相對于當前活動窗口左上角的位置event->globalPos()獲取的鼠標位置是鼠標偏離電腦屏幕左上角(x=0,y=0)的位置;一般不采用前者,使用前者,拖動準確性較低且會產生抖動。*/} }void Widget::mouseReleaseEvent(QMouseEvent *event) {if(event->button() == Qt::LeftButton){m_bDrag = false;} }需要特別注意:在鼠標移動過程中必須通過buttons()來判斷是哪個按鍵按下。因為button函數:
總結
以上是生活随笔為你收集整理的QMouseEvent的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QT自定义控件之倒计时控件
- 下一篇: 2022我会成为高手吗