1. 程式人生 > >Qt學習筆記(1)---QT5利用事件過濾器實現在控制元件上繪圖

Qt學習筆記(1)---QT5利用事件過濾器實現在控制元件上繪圖

首先,感謝 作者:一去丶二三裡 部落格地址:http://blog.csdn.net/liang19890820  

Qt中要在控制元件中繪製圖像,需要重寫paintevent函式,本文通過EventFilter(事件過濾器)來實現在控制元件上的圖形繪製。

.h檔案

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QPointF>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

public slots:
    bool eventFilter(QObject *, QEvent *);

private:
    Ui::Widget *ui;
    bool mouseIsdown;
    QPointF startPos;
    QPointF endPos;
};

#endif // WIDGET_H
.cpp檔案
#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QMouseEvent>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    mouseIsdown = false;
    ui->label->installEventFilter(this);

}

Widget::~Widget()
{
    delete ui;
}


bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->label )
    {
        if(event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent *mouseEvent=(QMouseEvent *)event;

            if(mouseEvent->buttons()&Qt::LeftButton)
            {
                mouseIsdown = true;
                startPos = mouseEvent->pos();
            }

        }
        if(event->type() == QEvent::MouseMove)
        {
            QMouseEvent *mouseEvent=(QMouseEvent *)event;

            if(mouseIsdown)
            {
                endPos = mouseEvent->pos();
                ui->label->update();
            }
        }

        if(event->type() == QEvent::MouseButtonRelease)
        {
            QMouseEvent *mouseEvent=(QMouseEvent *)event;

            endPos = mouseEvent->pos();
            mouseIsdown = false;

        }
        if(event->type() == QEvent::Paint)
        {

            QPainter painter(ui->label);

            QPen pen = painter.pen();

            pen.setWidth(3);
            pen.setColor(QColor(173, 255, 47));
            //反走樣
            painter.setRenderHint(QPainter::Antialiasing, true);
            painter.setPen(pen);
            // 繪製直線
            painter.drawLine(startPos, endPos);

        }
    }

    return QWidget::eventFilter(watched,event);
}

eventFilter(QObject *watched, QEvent *event)中

watched為事件過濾器的物件即本文中的label , event 為事件型別。

其中需要注意的有兩點:

1.在建構函式中新增過濾器installEventFilter(this)如果一個控制元件添加了多個過濾器,後新增會被選擇執行。

2.返回父類的eventfliterreturn QWidget::eventFilter(watched,event);