質問

定期的に長方形の中でテキストの色を変更したいです。これが私の裁判です:

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

幸運を

他のヒント

qgraphicsitemはqobjectから派生しているわけではないため、タイマーイベントを処理するために必要なイベントキューがありません。使用してみてください qgraphicsobject またはqgraphicsitemとqobjectの複数の継承(これはまさにqgraphicsobjectが行うことです)。

タイマーが適切に初期化されているかどうかを確認してください。

ペイントに使用されるブラシの色を変更してみてください。

自宅で自由時間があるときにあなたのコードをチェックしますが、それは日曜日までにはありません。

ベースポイントとして、あなたは見ることができます ウィグリーの例 そして、あなた自身のコードでいくつかのエラーを見つけてください。 QTにとって、私の意見では、時々見るのは良い習慣です 例とデモ 応用。

幸運を!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top