【问题标题】:Update a specific QGraphicsObject by moving other objects通过移动其他对象来更新特定的 QGraphicsObject
【发布时间】:2012-05-12 15:29:09
【问题描述】:

我想在QGraphicsView 中显示一个有限自动机。子类化QGraphicsItem 我有一个代表状态的类:Node,它包含指向Link 实例的指针,这些实例指定状态之间的移动。每个链接还包含其起点和终点(指向Node 实例的指针)。

我希望我的代码通过移动其中一个状态来更新(重绘)链接。我找不到调用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());
}

【问题讨论】:

    标签: qt4 qgraphicsview qgraphicsitem


    【解决方案1】:

    由于您的链接似乎是连接节点,因此您需要使用 ItemPositionChange 而不是 ItemPositionHasChanged,因为 ItemPositionChange 将在用户移动项目时被调用。

    然后您应该更新链接的位置,以便它仍然连接到您的节点并调用它的 update()。

    所以你的问题是 ItemPositionHasChanged 应该是 ItemPositionChange,而且你想在链接改变时更新节点,而不是当节点改变时我可以告诉。

    【讨论】:

      猜你喜欢
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      相关资源
      最近更新 更多