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();
}