Qt绘制五角星

利用Qt中的paintEvent事件绘制五角星
class DrawStar : public QWidget
{
Q_OBJECT
public:
explicit DrawStar(QWidget* parent = nullptr);

protected:
void paintEvent(QPaintEvent* pEvent);

private:
void initData();

private:
QPoint m_starData[5];
};

DrawStar::DrawStar(QWidget* parent)
QWidget(parent)
{
this->initData();
update();
}

void DrawStar::initData()
{
qreal deg = ((360 / 5) * 3.1415926) / 180;
qreal r = 100;

m_starData[0] = QPoint(r, 0);
m_starData[1] = QPoint(r * qCos(deg), -r * qSin(deg));
m_starData[2] = QPoint(r * qCos(2 * deg), -r * qSin(2 * deg));
m_starData[3] = QPoint(r * qCos(3 * deg), -r * qSin(3 * deg));
m_starData[4] = QPoint(r * qCos(4 * deg), -r * qSin(4 * deg));

}

void DrawStar::paintEvent(QPaintEvent* pEvent)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(Qt::black);
painter.setBrush(QBrush(Qt::yellow));

QPainterPath paintPath;
paintPath.moveTo(m_starData[3]);
paintPath.lineTo(m_starData[1]);
paintPath.lineTo(m_starData[4]);
paintPath.lineTo(m_starData[2]);
paintPath.lineTo(m_starData[0]);
paintPath.closeSubpath();
painter.translate(100, 100);


QFont font;
font.setPointSizeF(12);
paintPath.addText(m_starData[0], font, "0");
paintPath.addText(m_starData[1], font, "1");
paintPath.addText(m_starData[2], font, "2");
paintPath.addText(m_starData[3], font, "3");
paintPath.addText(m_starData[4], font, "4");
painter.setFont(font);	
painter.drawPath(paintPath);

}

你可能感兴趣的:(qt,开发语言)