Qt学习: QPaintEvent和QMouseEvent的简单程序示例

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)
{
if (sign)
    {
    //保存鼠标移动的时候的尾坐标.
    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();
        sign = false;
    }
}

void c::mousePressEvent(QMouseEvent *event)
{
    //当左键被按下时,保存首坐标.并更新重绘.
    if (event->button() == Qt::LeftButton)
    {
        //点击的时候定下初始位置.
        this->start = event->pos();
        sign = true;
    }
}

“c.h”的代码:

#ifndef C_H
#define C_H

#include 
#include "ui_c.h"
#include 
#include 
#include 
#include 
#include 
#include 

class c : public QMainWindow
{
    Q_OBJECT

public:
    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;
    bool sign = false;
};

#endif // C_H

最后是”main.cpp”下的代码:

#include "c.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    c w;
    w.show();
    return a.exec();
}

你可能感兴趣的:(Qt)