QGraphicsItem redraws

I want to periodically change the color of the text inside the rectangle. Here is my test:

 TrainIdBox::TrainIdBox()
 {
   boxRect = QRectF(0,0,40,15);
   testPen = QPen(Qt:red);
   i=0;
   startTimer(500);
 }

QRectF TrainIdBox::boundingRect() const
{
 return boxRect;
}

void TrainIdBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,   QWidget *widget)
{
  Q_UNUSED(widget);
  Q_UNUSED(option);

  painter->setPen(QPen(drawingColor,2));
  painter->drawRect(boxRect);
  painter->setPen(testPen);
  painter->drawText(boxRect,Qt::AlignCenter,"TEST");

 }
 void TrainIdBox::timerEvent(QTimerEvent *te)
 {
  testPen = i % 2 == 0 ? QPen(Qt::green) : QPen(Qt::yellow);
  i++;
  update(boxRect);
 }

This code does not work correctly. What's wrong?

+3
source share
4 answers

If you inherit from QGraphicsObject ... I will give an example here:

Declare:

 class Text : public QGraphicsObject
    {
        Q_OBJECT

    public:
        Text(QGraphicsItem * parent = 0);
        void paint ( QPainter * painter,
                     const QStyleOptionGraphicsItem * option, QWidget * widget  );
        QRectF boundingRect() const ;
        void timerEvent ( QTimerEvent * event );

    protected:
        QGraphicsTextItem * item;
        int time;
    };

implementation:

Text::Text(QGraphicsItem * parent)
    :QGraphicsObject(parent)
{
    item = new QGraphicsTextItem(this);
    item->setPlainText("hello world");

    setFlag(QGraphicsItem::ItemIsFocusable);    
    time  = 1000;
    startTimer(time);
}

void Text::paint ( QPainter * painter,
                   const QStyleOptionGraphicsItem * option, QWidget * widget  )
{
    item->paint(painter,option,widget);    
}

QRectF Text::boundingRect() const
{
    return item->boundingRect();
}

void Text::timerEvent ( QTimerEvent * event )
{
    QString timepass = "Time :" + QString::number(time / 1000) + " seconds";
    time = time + 1000;
    qDebug() <<  timepass;
}

luck

+2
source

QGraphicsItem is not derived from QObject and therefore does not have an event queue that is needed to handle timer events. Try using a QGraphicsObject or multiple inheritance from QGraphicsItem and QObject (this is exactly what QGraphicsObject does).

+3
source

, 0.

, .

, , .

0

As a base point, you could look at the Wiggly Example and find some errors in yourself, which is much better. For Qt, in my opinion, it’s good practice to look at Examples and Demos in the application .

Good luck

0
source

Source: https://habr.com/ru/post/1747987/


All Articles