基于QGraphicsItem 抽象出一组类,并且支持扩展
时间: 2024-05-15 13:15:17 浏览: 44
QGraphicsItem是Qt中用于在图形界面中显示图形元素的基类。基于QGraphicsItem可以抽象出一组类,并且支持扩展,下面是一个示例:
1.创建一个基类MyItem,继承自QGraphicsItem:
```
class MyItem : public QGraphicsItem
{
public:
MyItem(QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) {}
virtual QRectF boundingRect() const override = 0;
virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override = 0;
};
```
2.根据需要,创建不同的子类,例如:
```
class CircleItem : public MyItem
{
public:
CircleItem(QGraphicsItem* parent = nullptr) : MyItem(parent) {}
virtual QRectF boundingRect() const override { return QRectF(-50, -50, 100, 100); }
virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override
{
painter->drawEllipse(-50, -50, 100, 100);
}
};
class RectItem : public MyItem
{
public:
RectItem(QGraphicsItem* parent = nullptr) : MyItem(parent) {}
virtual QRectF boundingRect() const override { return QRectF(-50, -50, 100, 100); }
virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override
{
painter->drawRect(-50, -50, 100, 100);
}
};
```
3.在主程序中创建对象并添加到场景中:
```
MyItem* item1 = new CircleItem();
MyItem* item2 = new RectItem();
QGraphicsScene* scene = new QGraphicsScene();
scene->addItem(item1);
scene->addItem(item2);
```
4.支持扩展,可以在子类中添加自定义的属性和方法:
```
class CircleItem : public MyItem
{
public:
CircleItem(QGraphicsItem* parent = nullptr) : MyItem(parent), m_color(Qt::red) {}
virtual QRectF boundingRect() const override { return QRectF(-50, -50, 100, 100); }
virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override
{
painter->setBrush(m_color);
painter->drawEllipse(-50, -50, 100, 100);
}
void setColor(const QColor& color) { m_color = color; }
private:
QColor m_color;
};
```
这样就可以在程序中通过调用setColor方法来改变圆形的颜色。
阅读全文