QGraphicsItem repaint
问题描述:
我想要定期更改矩形内的文本颜色。 这是我的试用版: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);
}
此代码无法正常工作。 有什么不对?
答
如果从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
尝试也可以用来刷涂料的变色。
我在家里有空闲时间的时候检查你的代码,但那不会在星期天之前。
答
QGraphicsItem不是从QObject派生的,因此没有事件队列,这是处理定时器事件所必需的。尝试使用QGraphicsObject或QGraphicsItem和QObject的多重继承(这正是QGraphicsObject的作用)。
我认为TrainIdBox从继承QGraphicsItem,至少在某处沿线?如果不是,它从哪里继承? – 2010-06-01 17:39:56