您好,登錄后才能下訂單哦!
QMouseEvent下可以被重寫的虛函數:
1.void mousePressEvent(QMouseEvent *event); //鼠標鍵被按下的事件.
2.void mouseReleaseEvent(QMouseEvent *event); //鼠標鍵被放開的事件.
3.void mouseMoveEvent(QMouseEvent *event); //按住鼠標鍵移動的事件.
4.void mouseDoubleClickEvent(QMouseEvent *event); //鼠標鍵被雙擊的事件.
QMouseEvent類中的重要函數:
1.QPoint pos(); //返回鼠標相對于父部件的坐標.
2.QPoint globalPos(); //返回鼠標的全局坐標.
3.QMouseButton button(); //返回鼠標被點擊的鍵.
“c.cpp”下的代碼:
#include "c.h"c::c(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); } c::~c() { }void c::mouseMoveEvent(QMouseEvent *event) { //保存鼠標移動的時候的尾坐標. end = event->pos(); //用來重繪更新.可以理解為調用paintEvent函數,但不一定是立即調用的.在此程序中可以理解為:馬上更新窗口上顯示的圖像. update(); }void c::paintEvent(QPaintEvent *event) { //畫一個矩形. QPainter painter(this); painter.setPen(Qt::red); QRect temp(start, end); painter.setBrush(Qt::green); painter.drawRect(temp); }void c::mouseReleaseEvent(QMouseEvent *event) { //當左鍵釋放后,保存尾坐標. if (event->button() == Qt::LeftButton) { this->end = event->pos(); update(); } }void c::mousePressEvent(QMouseEvent *event) { //當左鍵被按下時,保存首坐標.并更新重繪. if (event->button() == Qt::LeftButton) { //點擊的時候定下初始位置. this->start = event->pos(); } }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
“c.h”的代碼:
#ifndef C_H#define C_H#include <QtWidgets/QMainWindow>#include "ui_c.h"#include <QPixmap>#include <QMouseEvent>#include <QMessageBox>#include <QPainter>#include <QPaintEvent>#include <QVector>class c : public QMainWindow { Q_OBJECTpublic: c(QWidget *parent = 0); ~c();protected: void mouseMoveEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void paintEvent(QPaintEvent *event);private: Ui::cClass ui; QPoint start; QPoint end; };#endif // C_H1234567891011121314151617181920212223242526272829303132
最后是”main.cpp”下的代碼:
#include "c.h"#include <QtWidgets/QApplication>int main(int argc, char *argv[]) { QApplication a(argc, argv); c w; w.show(); return a.exec(); }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。