-1

I have a QGraphicsItem element (subclassesed from QGraphicsItem) that has as child a QGraphicsTextItem.

The problem is that the paint(...) method of the QGraphicsItem is called infinitely.

Here is the paint method from my QGraphicsItem element with the QGraphicsTextItem:

void rectangle_element::paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget )
{
    painter->drawRoundedRect( -10, -10, 80, 40, 5, 5 );
    painter->drawStaticText( -10, -10, QStaticText( "some text" ) );
    text_item->setPlainText( "more text" );
}

I cannot use setCacheMode with other flag than QGraphicsItem::CacheMode::NoCache.

I'm using Qt 5.6.

UPDATE:

  • The text_item is a member of the class and it is initialized in the initialization list.
mtb
  • 1,350
  • 16
  • 32
  • 2
    Why do you create a child every time you paint? Create the child in the constuctor – Fabio Sep 01 '16 at 14:35
  • @Fabio - updated the question. The `QGraphicsTextItem` is a member of the calss. – mtb Sep 01 '16 at 14:38
  • 1
    Again, why do you set the child text every time the item is painted? – Fabio Sep 01 '16 at 14:45
  • 3
    So every time the rectangle is painted, you set the text of `text_item`. This might cause a repaint of the parent item, which might be the reason for the infinite loop. Generally, it's not a good idea to change items during paint operations. Keep in mind that the `paint` method can be called with a high frequency. – Karsten Koop Sep 01 '16 at 14:45
  • @Karsten Koop But how can I update the text of the `text_item` then? – mtb Sep 01 '16 at 15:00
  • 1
    Depends on when it is supposed to be changed. If the text is the same during the lifetime of the item, set it at creation time. Otherwise, there will probably some kind of event which triggers the change of the text, so set the text there. The painting of the text itself should be handled by the `QGraphicsTextItem`. – Karsten Koop Sep 01 '16 at 15:04
  • @KarstenKoop Please add an answer based on your comments and I will accept it as solution. Thank you. – mtb Sep 02 '16 at 06:50

1 Answers1

2

You set the text of text_item in the paint() method of the parent item, which seems to in turn trigger a repaint of the parent, thus creating an infinite loop. Generally, it's not a good idea to change items during paint operations. Keep in mind that the paint() method can be called with a high frequency.

Probably there is some event triggering the need for a text change of text_item, like user interaction, which in turn calls a slot. This is the point where you should set the text. The drawing of the text itself is handled by the QGraphicsTextItem.

Karsten Koop
  • 2,475
  • 1
  • 18
  • 23