上一篇文章讲到创建一个Qt的窗口工程。今天我们来实现在窗口上画图,为什么是绘图呢?
当初我学计算机图形学的时候最先接触的就是绘图,所以就先讲绘图。
在窗口上绘图的主要方式是重载窗口类的paintEvent(QPaintEvent *event)来实现的。注意包含<QPaintEvent>和<QPainter>。
既然是在窗口上画画,那窗口就是画布是纸,当然就需要一支画笔来进行绘画。
在paintEvent的实现区域加上QPainter pt(this);或者QPainter *pt=new QPainter(this);
QPainter的构造函数是这样的QPainter(QPaintDevice *)。可以理解为准备一种画笔,然后把画布(窗口)绑定在笔上,让笔知道该往哪里画。QPaintDevice是QWidget的基类之一。
然后我们对画笔进行设置,我们对画笔的设置主要是通过设置QPen来实现的。
所以添加上QPen pen;
为了给封闭图形填充颜色,还需要定义画刷QBrush brush;


除了可以一个一个画这些图像,还可以选择用QPainterPath保存多个图形,然后一起画出来


除了以上功能,QPainter 还能实现旋转,平移,缩放变换,不过因为这个变换几乎可以说是整体变换,所以不建议使用,建议是对要画的图元本身进行修改。
除了对窗口进行绘图,QPainter还可以对其他对象绘图,比如说图片类、打印机。

非常重要的一点是,理论上QPainter只有在paintEvent函数中才能使用,在其他地方使用会导致QPainter对象失去活性。如果非要在其他地方使用,可以使用上面这种使用方式,虽然运行的时候还是会不断发出警告,但是不影响实际功能。
另外,使这个重载函数执行的条件的调用updata();或者repaint();或者窗口消失、出现、放大缩小、移动时。
网友评论