2010-06-01 71 views
3

我想要定期更改矩形內的文本顏色。 這是我的試用版:QGraphicsItem repaint

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

此代碼無法正常工作。 有什麼不對?

+0

我認爲TrainIdBox從繼承QGraphicsItem,至少在某處沿線?如果不是,它從哪裏繼承? – 2010-06-01 17:39:56

回答

2

如果從QGraphicsObject繼承......我在這裏給出一個例子:

聲明:本

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

實現:

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

好運

0

檢查定時器是否被正確初始化,它不應該返回0

嘗試也可以用來刷塗料的變色。

我在家裏有空閒時間的時候檢查你的代碼,但那不會在星期天之前。

0

作爲基點,你可以看到Wiggly Example並發現一些錯誤,你自己編碼,有什麼更好。對於Qt,在我看來,這是一個很好的做法,有時看看示例和演示應用程序。

祝你好運!

3

QGraphicsItem不是從QObject派生的,因此沒有事件隊列,這是處理定時器事件所必需的。嘗試使用QGraphicsObject或QGraphicsItem和QObject的多重繼承(這正是QGraphicsObject的作用)。