QGraphicsItem画五角星 C++
时间: 2023-09-11 20:04:16 浏览: 54
下面是用QGraphicsItem绘制五角星的代码示例:
```cpp
#include <QGraphicsItem>
#include <QPainter>
class StarItem : public QGraphicsItem
{
public:
StarItem(QGraphicsItem *parent = nullptr) : QGraphicsItem(parent) {}
QRectF boundingRect() const override
{
return QRectF(-50, -50, 100, 100);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->setRenderHint(QPainter::Antialiasing);
const qreal angle = M_PI / 5.0; // 五角星的每个角对应的角度
const qreal radius = 50; // 五角星的外接圆半径
// 绘制五角星
QPainterPath path;
path.moveTo(radius * qCos(3 * angle), radius * qSin(3 * angle));
for (int i = 0; i < 5; ++i) {
path.lineTo(radius * qCos((3 + i * 2) * angle), radius * qSin((3 + i * 2) * angle));
}
path.closeSubpath();
painter->drawPath(path);
}
};
```
在使用此类时,只需将其添加到场景或其他QGraphicsItem的子项中即可:
```cpp
QGraphicsScene scene;
StarItem *starItem = new StarItem;
scene.addItem(starItem);
```