2010-06-01 73 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的作用)。