QPainter 是一个画家,需要一个画板(QPaintDevice)才能在上面画画。而class Q_WIDGETS_EXPORT QWidget : public QObject, public QPaintDevice,因此所有的窗口都是画板。画家可以设置画笔,画刷,字体这个工具参数。同时还可以整体平移旋转画板。
class Q_GUI_EXPORT QPixmap : public QPaintDevice:QPixmap是一个画板,因此可以将所有的画画内容先画到pixmap上,然后再窗口上画一个pixmap既可,这样可以提高效率。
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
void paintEvent(QPaintEvent *);
void mousePressEvent(QMouseEvent *);
signals:
public slots:
};
#endif // MYWIDGET_H
#include "MyWidget.h"
#include <QPainter>
#include <QPixmap>
MyWidget::MyWidget(QWidget *parent) :
QWidget(parent)
{
}
void MyWidget::paintEvent(QPaintEvent *)
{
QPixmap pixmap(size());
QPainter p(&pixmap);
// p.translate(100, 100);
//p.scale();
p.setRenderHint(QPainter::Antialiasing);
QTransform transform;
transform.translate(50,50);
transform.rotate(30);
// transform.scale(.5, .5);
p.setTransform(transform);
#if 1
QTransform transform2;
transform2.scale(.5, .5);
p.setTransform(transform2, true);
#endif
p.drawLine(QPoint(0, 0), QPoint(100, 100));
// p.translate(-100, -100);
p.setPen(QPen(Qt::red, 2, Qt::DashLine));
p.setBrush(Qt::yellow);
p.setFont(QFont("aaa", 40, 700, true));
p.drawEllipse(QPoint(95, 333), 50, 50);
p.drawText(QPoint(300, 50), "Hello world");
// p.drawPixmap(QPoint(40, 40), QPixmap("../aaa.png"));
// p.drawRect(QRect(40, 60, 100, 50));
p.drawRoundRect(QRect(40, 60, 100, 50));
p.end();
p.begin(this);
p.drawPixmap(0, 0, pixmap);
}
void MyWidget::mousePressEvent(QMouseEvent *)
{
QPixmap pixmap(size());
QPainter painter(&pixmap);
render(&painter);
pixmap.save("../Painter.png");
}
#include <QApplication>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
MyWidget w;
w.show();
return app.exec();
}