);
运行程序,结果并没有在 Label 上绘制出矩形,而且还输出了下面的错误:
QPainter::begin: Paint device returned engine == 0, type: 1
QPainter::setPen: Painter not active
QPainter::setBrush: Painter not active
QPainter::drawRects: Painter not active
QPainter::begin: Paint device returned engine == 0, type: 1
上面1(2)提到了想要在哪个 widget 上绘图,就需要在它的 paintEvent() 函数里绘图,这里我们是想在这个Qlabel中绘图,但是paintEvent()函数是PainterTest的,所以绘制出了问题绘制不成功。
因此想要在QLabel中绘制图形,就必须新建一个类继承自QLAbel,然后在它的 paintEvent() 里绘图,如果单独就这个问题创建一个新的类就会有点小题大作了
在事件过滤器 eventFilter()
中拦截 QLabel 的 QEvent::Paint
事件,用 QLabel 创建 QPainter,就可以在 QLabel 上绘图了
PaintTest.h
1 #ifndef PAINTTEST_H
2 #define PAINTTEST_H
4 #include <QWidget>
5 #include <QLabel>
6 #include <QPainter>
7 class PaintTest : public QWidget
9 Q_OBJECT
10 private:
11 QLabel *la;
12 public:
13 explicit PaintTest(QWidget *parent = 0);
14 // void paintEvent(QPaintEvent *);
15 bool eventFilter(QObject *watched, QEvent *event) ;
16 void magicTime();
17 signals:
19 public slots:
21 };
22 #endif // PAINTTEST_H
PaintTest.cpp
1 #include "PaintTest.h"
2 #include <QLabel>
3 #include <QEvent >
4 PaintTest::PaintTest(QWidget *parent) :
5 QWidget(parent),la(new QLabel(this))
7 //la=new QLabel(this);
9 la->setText("PaintTest Label");
10 la->resize(100,190);
12 la->installEventFilter(this);
13 }
14 /*void PaintTest::paintEvent(QPaintEvent *) {
15 QPainter painter(this); // this 是 PaintTest 的指针
16 QPainter painter(this->la);
17 painter.setPen(Qt::gray);
18 painter.setBrush(Qt::green);
19 painter.drawRect(10, 10, 50, 50);
20 }*/
22 bool PaintTest::eventFilter(QObject *watched, QEvent *event) {
23 if (watched == this->la && event->type() == QEvent::Paint) {
24 magicTime();
25 }
27 return QWidget::eventFilter(watched, event);
28 }
30 void PaintTest::magicTime() {
31 QPainter painter(this->la );
32 painter.setPen(Qt::gray);
33 painter.setBrush(Qt::green);
34 painter.drawRect(10, 10, 50, 50);