# 绘制系统组件 ​ QT中的绘画系统依赖于三个类:画家`QPainter`、画布`QPainterDevice`和绘画引擎`QPaintEngine`。 ​ `QPainter`是绘画指令的操作者,一切绘画操作由`QPainter`完成。 ​ `QPaintDevice`是一个二维空间的抽象,代表了屏幕上的一个可绘制区域。由于`QPaintDevice`类型繁多(如QImage、QWidget、QPdf等),因此使用`QPaintEngine`翻译来自`QPainter`的指令,以便为所有设备提供相同的绘制操作。 **QT中绘画流程:** ![1560072619024](assets/1560072619024.png) ## 绘图事件与其发生时机 ​ QT中的绘制系统能且只能运行在绘图事件中,若绘图操作运行在非绘图事件中,则代码无效。 ​ 每当程序最大化、最小化或由阻挡变为完全时也会进行绘制。手动调用绘图事件的方法为调用`update()`函数。 例: ```c++ #include #include #include class PaintEv : public QWidget { Q_OBJECT public: PaintEv(QWidget *parent = nullptr); ~PaintEv(); protected: void paintEvent(QPaintEvent*e)override; }; // PaintEv::PaintEv(QWidget *parent) : QWidget(parent) { this->resize(600,200); } void PaintEv::paintEvent(QPaintEvent *e) { QPainter painter(this); painter.setPen(Qt::red); painter.drawLine(0,0,600,200); painter.drawRect(20,20,50,50); } ``` ![1560073223774](assets/1560073223774.png)