【问题标题】:Qt update() doesn't workQt 更新()不起作用
【发布时间】:2014-05-18 23:15:48
【问题描述】:

我有一个问题,QGraphicsItem 中的 update() 函数不起作用。我想要做的是,当我移动 circle 时,其他 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() 正常工作。

【问题讨论】:

  • 您到底期望发生什么,实际发生了什么?
  • 从我的代码中,您可以看到,当圆圈移动时,我正在设置布尔变量“更改背景”,然后我必须重新绘制圆形矩形,这就是我调用 update() 的原因在圆圈移动时更改 roundrect 的背景颜色。

标签: c++ qt qgraphicsview qgraphicsitem


【解决方案1】:

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

QGraphicsView * parent;

当您希望更改发生时调用它的更新方法,例如:

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

【讨论】:

  • 为什么我不能从 QGraphicsItem 类中调用 update() 方法?并创建一个视图并通过视图更新父母?为什么?为什么调用 graphicsitem 更新不起作用而 graphicsview 会?顺便说一句 QGraphicsView ,没有 update() 方法,只是查看了文档。
  • 虽然它有一个函数ViewportUpdateMode,但mb重载这个函数rly会有所帮助。
  • update() 方法是从 QWidget 派生的。您应该通过更新整个视图或场景来强制更新。 QGraphicsItem 的 update() 方法只是安排重绘。 QGraphicsView 调用paint() 函数来绘制项目的内容。
  • 好的,现在我遇到了一个问题,我的类继承自 QGraphicsItem 并且此更新需要 QWidget,让我们考虑一下。
  • 您需要一个 QGraphicsScene 和一个 QGraphicsView 对象来显示您的项目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-19
  • 2011-04-05
  • 2010-10-03
  • 2016-08-04
相关资源
最近更新 更多