首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QGraphicsItem重绘

QGraphicsItem重绘
EN

Stack Overflow用户
提问于 2010-06-01 21:35:11
回答 4查看 6.5K关注 0票数 3

我想定期更改矩形内的文本颜色。这是我的试验:

代码语言:javascript
复制
 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);
 }

此代码无法正常工作。怎么啦?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-10-14 05:32:05

如果你从QGraphicsObject继承...我在这里举个例子:

声明:

代码语言:javascript
复制
 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;
    };

实施:

代码语言:javascript
复制
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;
}

祝好运

票数 2
EN

Stack Overflow用户

发布于 2010-06-14 08:37:32

QGraphicsItem不是从QObject派生的,因此没有处理计时器事件所需的事件队列。尝试使用QGraphicsObject或QGraphicsItem和QObject的多重继承(这正是QGraphicsObject所做的)。

票数 3
EN

Stack Overflow用户

发布于 2010-06-01 22:42:09

检查计时器是否正确初始化,不应返回0。

同时尝试更改用于绘画的画笔的颜色。

当我在家里有空闲时间时,我会检查你的代码,但那不会在周日之前。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2950194

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档