0
我想在QGraphicsView
中顯示有限自動機。子類QGraphicsItem
我有一個代表狀態的類:Node
它保存指向Link
實例的指針,指定狀態之間的移動。每個鏈接還包含其起始和目的地(指向Node
實例的指針)。通過移動其他對象來更新特定的QGraphicsObject
我希望我的代碼通過移動其中一個狀態來更新(重繪)鏈接。我無法找到一種方法來撥打paint()
或以某種方式強制鏈接更新。
節點實現:
Node::Node(QGraphicsItem * parent) :
QGraphicsObject(parent)
{
setFlag(ItemIsMovable);
setFlag(ItemSendsGeometryChanges);
setCacheMode(DeviceCoordinateCache);
setZValue(-1);
}
void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QPen pen(Qt::black);
if(option->state & QStyle::State_Selected)
{
pen.setStyle(Qt::DotLine);
pen.setWidth(2);
}
painter->setPen(pen);
painter->drawEllipse(-m_size.width()/2,-m_size.height()/2,m_size.width(),m_size.height());
painter->drawText(boundingRect(),Qt::AlignCenter,m_label);
}
QRectF Node::boundingRect() const
{
return QRectF(topLeft(),m_size);
}
//...
void Node::addLink(Link* newLink)
{
links.append(newLink);
}
// protected members
QVariant Node::itemChange(GraphicsItemChange change, const QVariant &value)
{
switch (change)
{
case ItemPositionHasChanged:
foreach (Link *link, links)
{
link->update(); // This has no effect
}
break;
default:
break;
};
return QGraphicsItem::itemChange(change, value);
}
鏈路實現:
Link::Link(QGraphicsItem *parent) :
QGraphicsObject(parent)
{
setFlag(ItemIsMovable);
setFlag(ItemSendsGeometryChanges);
setCacheMode(DeviceCoordinateCache);
setZValue(-1);
}
Link::Link(Node *From, Node *To, QGraphicsItem *parent):
QGraphicsObject(parent),
from(From),
to(To)
{
setFlag(ItemIsMovable);
setFlag(ItemSendsGeometryChanges);
setCacheMode(DeviceCoordinateCache);
setZValue(-1);
}
void Link::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
m_painter = painter;
QPen pen(Qt::black);
if(option->state & QStyle::State_Selected)
{
pen.setStyle(Qt::DotLine);
pen.setWidth(2);
}
painter->setPen(pen);
painter->drawLine(from->pos(),to->pos());
}
QRectF Link::boundingRect() const
{
return QRectF(from->pos(),to->pos());
}