qt函数绘制器的具体代码
时间: 2023-08-14 08:08:25 浏览: 87
以下是一个使用Qt绘制器绘制简单图形的示例代码:
```C++
#include <QPainter>
#include <QPen>
#include <QBrush>
#include <QColor>
#include <QPixmap>
#include <QWidget>
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = nullptr) : QWidget(parent) {}
protected:
void paintEvent(QPaintEvent *event) override
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing); // 抗锯齿
// 绘制直线
QPen linePen(Qt::red, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
painter.setPen(linePen);
painter.drawLine(50, 50, 200, 50);
// 绘制矩形
QPen rectPen(Qt::blue, 2, Qt::DashLine, Qt::RoundCap, Qt::RoundJoin);
painter.setPen(rectPen);
QBrush rectBrush(QColor(255, 0, 0, 127), Qt::DiagCrossPattern);
painter.setBrush(rectBrush);
painter.drawRect(50, 100, 150, 100);
// 绘制椭圆
QPen ellipsePen(Qt::green, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
painter.setPen(ellipsePen);
QBrush ellipseBrush(QColor(0, 255, 0, 127), Qt::SolidPattern);
painter.setBrush(ellipseBrush);
painter.drawEllipse(50, 250, 150, 100);
// 绘制多边形
QPen polygonPen(Qt::black, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
painter.setPen(polygonPen);
QBrush polygonBrush(QColor(0, 0, 255, 127), Qt::SolidPattern);
painter.setBrush(polygonBrush);
QPointF points[4] = {QPointF(300, 50), QPointF(350, 150), QPointF(400, 100), QPointF(350, 50)};
painter.drawPolygon(points, 4);
// 绘制圆弧
QPen arcPen(Qt::magenta, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
painter.setPen(arcPen);
QBrush arcBrush(QColor(255, 255, 0, 127), Qt::SolidPattern);
painter.setBrush(arcBrush);
painter.drawArc(300, 200, 100, 100, 30 * 16, 120 * 16);
// 绘制图像
QPixmap pixmap(":/images/qt-logo.png");
painter.drawPixmap(300, 350, pixmap);
}
};
```
在上面的代码中,我们继承了QWidget类,并重写了它的paintEvent函数。在paintEvent函数中,我们首先创建了一个QPainter对象,并设置了一些绘图属性,例如抗锯齿、线条样式、填充样式等等。之后,我们使用QPainter的绘图函数绘制了直线、矩形、椭圆、多边形和圆弧。最后,我们还绘制了一个图像。
阅读全文