【发布时间】:2015-06-02 04:14:08
【问题描述】:
我有一个对象类型的层次结构,继承自自定义接口和QGraphicsItem。
为了优化代码,我想继承QGraphicsSomethingItem。示例:矩形
class RectangleItem : public Item, public QGraphicsItem
{
RectangleItem() : Item() // Item initializes m_pen, m_brush
{
setFlags(QGraphicsItem::ItemIsMovable |
QGraphicsItem::ItemIsFocusable |
QGraphicsItem::ItemIsSelectable);
}
QRectF RectangleItem::boundingRect() const
{
return QRectF(-50, -50, 100, 100);
}
void RectangleItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
setItemPen(); // calculates m_pen in class Item
setItemBrush(); // calculates m_brush in class Item
painter->setPen(m_pen);
painter->setBrush(m_brush);
painter->drawRect(boundingRect());
}
}
这很好用。
现在尝试同样的事情,但继承自 QGraphicsRectItem
class RectangleItem : public Item, public QGraphicsRectItem
{
RectangleItem() : Item() // Item initializes m_pen, m_brush
{
setRect(-50, -50, 100, 100);
setFlags(QGraphicsItem::ItemIsMovable |
QGraphicsItem::ItemIsFocusable |
QGraphicsItem::ItemIsSelectable);
}
QRectF RectangleItem::boundingRect() const
{
return QRectF(-50, -50, 100, 100);
}
void RectangleItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
// setItemPen(); // calculates m_pen in class Item
// setItemBrush(); // calculates m_brush in class Item
setPen(m_pen);
setBrush(m_brush);
QGraphicsRectItem::paint(painter, option, widget);
}
}
这会创建一个无限循环
- setItemPen() 上的断点显示它一直在调用它。所以我把它和setItemBrush() 一起删除了。 (虽然我真的需要设置自定义笔)
- setPen() 上的断点显示它一直在调用它。所以我删除了它。与setBrush()相同
- 一旦没有东西被“固定”在油漆内,油漆就起作用了。
当然,这不起作用——我需要能够设置项目属性,我的理解是调用paint()——在调用更新场景时发生——会更新他的项目。毕竟,我的第一个示例,继承自 QGraphicsItem,有效。
我在question 中发现了类似的东西 - 但没有关于如何修复它的答案,或者没有实际解释为什么调用设置笔和画笔会导致重绘。该代码中没有使用任何项目的绘图属性,甚至更多 - 如果我使用构造函数中的值调用 setPen(m_pen),我看不到需要重新计算...
什么会触发对象重绘以及如何避免它?
【问题讨论】:
标签: qt inheritance paint