C++ Qt update()不';行不通

C++ Qt update()不';行不通,c++,qt,qgraphicsview,qgraphicsitem,C++,Qt,Qgraphicsview,Qgraphicsitem,我有一个问题,QGraphicsItem中的update()函数不起作用。我想做的是,当我移动圆圈时,其他QGraphicsItem(同时roundrect)会改变颜色。 这是一个例子,我想做的是: circle.cpp: void CircleItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { // RoundRect Object RectItem->SetBackGround(); QGraphics

我有一个问题,
QGraphicsItem
中的update()函数不起作用。我想做的是,当我移动圆圈时,其他
QGraphicsItem
(同时roundrect)会改变颜色。 这是一个例子,我想做的是:

circle.cpp:

void CircleItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    // RoundRect Object
    RectItem->SetBackGround();
    QGraphicsItem::mouseMoveEvent( event );
}
RoundRect.cpp:

void RoundRectItem::SetBackGround()
{
    ChangeBackground = true;
    update();
}

void RoundRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QRectF rec = QRectF( QPoint( 0,0 ), boundingRect().size() / 2 );

    roundRect = QRectF(rec.adjusted(-rec.height() / 2, 0, rec.height()/2, 0));

    roundRect.moveTo( boundingRect().center().x() - roundRect.width() / 2,
                      boundingRect().center().y() - roundRect.height() / 2 );

    if( !ChangeBackground )
        painter->setBrush( backBrush );
    else
        painter->setBrush( QBrush( Qt::blue ) );

    painter->setPen( QColor( 255,255,255 ) );

    painter->drawRoundedRect(roundRect, roundRect.height() / 2, roundRect.height() / 2 );
}

所以问题是,我如何才能使这个
update()
正常工作。

您正在调用QGraphicsItem的update()方法。您应该调用正在使用的QGraphicsView的update()。例如,您可以将QGraphicsView保留为项目的成员类,如:

QGraphicsView * parent;
并在希望更改发生时调用其更新方法,如:

void RoundRectItem::SetBackGround()
{
    ChangeBackground = true;
    parent->update();
}

你到底期望发生什么,以及实际发生了什么?从我的代码中,你可以看到,当圆移动时,我正在设置bool varible“Change Background”,然后我必须重新绘制roundrect,这就是为什么我调用update()来更改roundrect的背景色,当圆圈移动时。为什么我不能从QGraphicsItem类调用update()方法?创建一个视图并按视图更新父视图?为什么?为什么调用graphicsitem更新不起作用,而graphicsview会起作用?顺便说一句,QGraphicsView没有update()方法,只是查看了文档。虽然它有一个函数ViewportUpdateMode,但mb重载这个函数会有所帮助。update()方法是从QWidget派生的。应该通过更新整个视图或场景来强制更新。QGraphicsItem的update()方法只是安排重新绘制。QGraphicsView调用paint()函数来绘制项目的内容。好了,现在我遇到了一个问题,我的类继承自QGraphicsItem,此更新需要QWidget,让我们考虑一下这个问题。您需要一个QGraphicsCenter和一个QGraphicsView对象来显示您的项目。