QGraphicsItem 重绘
我想定期更改矩形内的文本颜色。 这是我的试用:
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);
}
此代码无法正常工作。 怎么了?
I want to change text color inside a rectangle periodically.
Here is my trial:
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 working properly.
What is wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
QGraphicsItem 不是从 QObject 派生的,因此没有处理计时器事件所需的事件队列。尝试使用 QGraphicsObject 或 QGraphicsItem 和 QObject 的多重继承(这正是 QGraphicsObject做)。
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).
如果你继承自 QGraphicsObject ...我在这里举一个例子:
声明:
实现:
祝你好运
If you inherit from QGraphicsObject ... I give here an example:
Declare:
implementation:
good luck
检查计时器是否正确初始化,它不应返回 0。
还可以尝试更改用于绘画的画笔的颜色。
当我在家有空闲时间时,我会检查你的代码,但不会在周日之前。
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.
作为基点,您可以观看 Wiggly 示例 并发现一些错误自己编码,还有什么更好的呢?对于 Qt,我认为,有时查看示例和演示应用程序是一个很好的做法。
祝你好运!
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!