QPainter 默认只能在paintEvent中进行绘制
这在有些情况下会很不方便,有时候我们希望可以在任意地方直接进行绘制
为了实现这个目的,可以采用以下方法:
继承QWidget,通过子类提供直接绘制的方法,并将所有绘制保存到中间的QPixmap
最后在重载的paintEvent中将QPixmap复制显示:
#pragma once #include <QtWidgets/QWidget> #include <QPainter> #include <QResizeEvent> class PaintWidget: public QWidget { Q_OBJECT public: PaintWidget(QWidget * parent = 0, Qt::WindowFlags f = 0) :QWidget(parent, f) { mPixmap = new QPixmap(width(), height()); mPainter = new QPainter(mPixmap); } ~PaintWidget() { delete mPainter; delete mPixmap; } void resizeEvent(QResizeEvent *event) { if(event->size().width() > mPixmap->width() || event->size().height() > mPixmap->height()) { QPixmap* pixmap = new QPixmap((std::max)(event->size().width(), mPixmap->width()), (std::max)(event->size().height(), mPixmap->height())); delete mPainter; mPainter = new QPainter(pixmap); mPainter->drawPixmap(0, 0, *mPixmap); delete mPixmap; mPixmap = pixmap; } } void paintEvent(QPaintEvent *event) { QPainter painter(this); painter.drawPixmap(0, 0, *mPixmap); } QPainter* getPainter() { return mPainter; } private: QPixmap* mPixmap; QPainter* mPainter; };
使用说明:
通过子类提供的getPainter()方法获取QPainter指针以便进行绘制,比如:
paintWidget.getPainter()->drawLine(...);
paintWidget.update() ; //绘制之后记得通过paintWidget.update() 通知页面刷新
附:代码中的resizeEvent是为了保证缓存的QPixmap始终比widget大,根据情况你可以直接初始化为所希望的大小