Pregunta

Quiero cambiar el color del texto dentro de un rectángulo de forma periódica. Aquí está mi ensayo:

 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);
 }

Este código no funciona correctamente. ¿Qué está mal?

¿Fue útil?

Solución

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

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;
}

good luck

Otros consejos

QGraphicsItem is not derived from QObject and hence does not have an event queue, which is needed to handle timer events. Try using QGraphicsObject or multiple inheritance of QGraphicsItem and QObject (which is exactly what QGraphicsObject does).

Check if Timer was properly initialized, it shouldn't return 0.

Try also changing color of brush used to paint.

I check your code when I get some free time in home, but that won't be before Sunday.

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

Good luck!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top