QPainter 绘制一些简单的图形,也可以设置文字,设置笔,路径等。需要实现paintEvent这个方法,然后使用QPainter需要传入this指针,表示父类会调用。
#include "basicshapewindow.h"
#include "ui_basicshapewindow.h"
BasicShapeWindow::BasicShapeWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::BasicShapeWindow)
{
ui->setupUi(this);
}
void BasicShapeWindow::paintEvent(QPaintEvent *event)
{
QPainter textPainter(this);
textPainter.setFont(QFont("Times", 14, QFont::Bold));
textPainter.drawText(QPoint(40, 60), "Testing");
QPainter linePainter(this);
linePainter.drawLine(QPoint(50, 60), QPoint(100, 100));
QPainter rectPainter(this);
rectPainter.setBrush(Qt::BDiagPattern);
rectPainter.drawRect(QRect(40, 120, 80, 130));
QPen ellipsePen;
ellipsePen.setColor(Qt::red);
ellipsePen.setStyle(Qt::DashDotLine);
QPainter ellipsePainter(this);
ellipsePainter.setPen(ellipsePen);
ellipsePainter.drawEllipse(QPoint(200, 100), 150, 70);
QPainterPath rectPath;
rectPath.addRect(QRect(150, 60, 100, 50));
QPainter pathPainter(this);
pathPainter.setPen(QPen(Qt::red, 3, Qt::DashDotLine, Qt::FlatCap, Qt::MiterJoin));
pathPainter.setBrush(Qt::yellow);
pathPainter.drawPath(rectPath);
QPainterPath ellipsePath;
ellipsePath.addEllipse(QPoint(200, 120), 50, 120);
QPainter ellipsePathPainter(this);
ellipsePathPainter.setPen(QPen(QColor(79, 106, 25), 5,
Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
ellipsePathPainter.setBrush(QColor(122, 163, 39));
ellipsePathPainter.drawPath(ellipsePath);
QImage image;
image.load(":/head.png");
QPainter imagePainter(this);
imagePainter.drawImage(QPoint(100, 150), image);
}
BasicShapeWindow::~BasicShapeWindow()
{
delete ui;
}