1.概要
2.代码
2.1 widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QPainter>QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();
protected:void paintEvent(QPaintEvent *event);private:Ui::Widget *ui;
};
#endif // WIDGET_H
2.2 widget.cpp
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);
}Widget::~Widget()
{delete ui;
}void Widget::paintEvent(QPaintEvent *event){QPainter painter(this);painter.setRenderHint(QPainter::Antialiasing);// 设置画笔颜色painter.setPen(Qt::black);// 设置画刷颜色(如果需要填充)painter.setBrush(Qt::lightGray);// 计算等边三角形的大小和位置int side = qMin(width(), height()) * 0.7; // 边长取窗口宽度和高度中较小值的70%int centerX = width() / 2;int centerY = height() / 2;// 计算等边三角形顶点的位置QPointF point1(centerX, centerY - side / 2.0 * sqrt(3.0) / 2.0);QPointF point2(centerX + side / 2.0, centerY + side / 2.0 * sqrt(3.0) / 2.0);QPointF point3(centerX - side / 2.0, centerY + side / 2.0 * sqrt(3.0) / 2.0);// 绘制等边三角形QPolygonF triangle;triangle << point1 << point2 << point3;painter.drawPolygon(triangle);
}
2.3 main.cpp
#include "widget.h"#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.show();return a.exec();
}