QGraphicsItem画五角星 C++
时间: 2024-01-24 19:08:18 浏览: 80
以下是使用QPainter和QPolygonF绘制五角星的示例代码:
```c++
#include <QGraphicsItem>
#include <QPainter>
class StarItem : public QGraphicsItem
{
public:
StarItem(QGraphicsItem *parent = nullptr) : QGraphicsItem(parent)
{
// 设置item的尺寸
setFlag(QGraphicsItem::ItemIsSelectable);
setFlag(QGraphicsItem::ItemIsMovable);
setFlag(QGraphicsItem::ItemSendsGeometryChanges);
setCacheMode(DeviceCoordinateCache);
setZValue(-1);
}
QRectF boundingRect() const override
{
// 返回item的边界矩形
return QRectF(-50, -50, 100, 100);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
// 绘制五角星
painter->setRenderHint(QPainter::Antialiasing);
painter->setPen(Qt::NoPen);
painter->setBrush(Qt::red);
const qreal r = 40;
const qreal deg = M_PI / 180.0;
QVector<QPointF> points;
for (int i = 0; i < 5; ++i) {
const qreal x = 50 + r * qSin(72 * i * deg);
const qreal y = 50 - r * qCos(72 * i * deg);
points << QPointF(x, y);
}
const QPolygonF polygon(points);
painter->drawPolygon(polygon);
}
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override
{
// 拖拽item时更新边界矩形
if (change == ItemPositionChange) {
QRectF newRect = boundingRect();
newRect.translate(value.toPointF());
return newRect.topLeft();
}
return QGraphicsItem::itemChange(change, value);
}
};
```
将此类添加到场景中后,将会绘制一个红色的五角星。
阅读全文