3

我创建了一个 Qt 项目,它在小部件上显示一个圆圈。然后我有一个方法,每次调用该方法时都会在不同的位置重绘圆。我想要的是在 for 循环中运行该方法,例如十次,并显示每秒钟重绘圆的 10 个位置中的每一个。

类似于以下内容:

void method::paintEvent(QPaintEvent * p)
{

//code

    for(int i=0; i<10;i++)//do this every second
    {
       method(circle[i]); //co-ordinates change
       circle[i].pain( & painter); //using QPainter
    }

//code

}

我读过 QTimer,但不知道如何使用它。并且睡眠功能不起作用。

4

4 回答 4

3

正如您已经猜到的,QTimer是在这里使用的正确机制。如何进行设置?

这是一个选项:

class MyClass : public QObject
{
   public:
   MyClass():i(0)
   {
       QTimer::singleShot(1000,this,SLOT(callback()));//or call callback() directly here
   } //constructor

   protected:
   unsigned int i;
   void paintEvent(QPaintEvent * p)
   {    
     //do your painting here  
   }

   public slots:
   void callback()
   {
      method(circle[i]); //co-ordinates change
      //circle[i].pain( & painter); //don't use QPainter here - call update instead
      update();
      ++i;//increment counter
      if(i<10) QTimer::singleShot(1000,this,SLOT(callback()));
   }

}
于 2014-04-15T18:48:33.043 回答
1

您需要做的就是update()从计时器事件中触发一个。该update()方法在小部件上调度 a paintEvent

在之外的小部件上绘画是无效的paintEvent- 这是我发布此答案时所有其他答案所做的错误。仅仅调用该paintEvent方法不是一种解决方法。你应该打电话update()。打电话repaint()也可以,但只有在您了解两者的区别update()并有充分理由这样做时才能这样做。

class Circle;

class MyWidget : public QWidget {
  Q_OBJECT
  QBasicTimer m_timer;
  QList<Circle> m_circles;
  void method(Circle &);
  void paintEvent(QPaintEvent * p) {
    QPainter painter(this);
    // WARNING: this method can be called at any time
    // If you're basing animations on passage of time,
    // use a QElapsedTimer to find out how much time has
    // passed since the last repaint, and advance the animation
    // based on that.
    ...
    for(int i=0; i<10;i++)
    {
       method(m_circles[i]); //co-ordinates change
       m_circles[i].paint(&painter);
    }
    ...
  }
  void timerEvent(QTimerEvent * ev) {
    if (ev->timerId() != m_timer.timerId()) {
      QWidget::timerEvent(ev);
      return;
    }
    update();
  }
public:
  MyWidget(QWidget*parent = 0) : QWidget(parent) {
    ...
    m_timer.start(1000, this);
  }
};
于 2014-04-16T18:56:58.250 回答
0

尝试这样的事情:

class MyDrawer : public QObject
{
    Q_OBJECT
    int counter;
    QTimer* timer;

public:
    MyDrawer() : QObject(), counter(10)
    {
        timer = new QTimer(this);
        connect(timer, SIGNAL(timeout()), this, SLOT(redraw()));
        timer->start(1000);
    }

public slots:
    void redraw()
    {
        method(circle[i]); //co-ordinates change
        circle[i].pain( & painter);

        --counter;
        if (counter == 0) timer->stop();
    }

};

不要忘记moc在这个文件上运行,尽管如果你的类是一个 QObject 你可能已经这样做了。

于 2014-04-15T18:48:11.220 回答
-1
Try this.

for(int i=0; i<10;i++)//do this every second
{
   method(circle[i]); //co-ordinates change
   circle[i].pain( & painter);
   sleep(1000);// you can also use delay(1000);

}

使用 sleep() 在其中声明的名为 sleep(int ms) 的函数使程序等待指定的毫秒时间。

于 2014-04-15T18:39:28.997 回答