如何每秒循环一个方法

如何每秒循环一个方法

本文介绍了QT:如何每秒循环一个方法? C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've created a Qt project which displays a circle on a widget.Then I have a method which redraws the circle at different positions every time I call the method.What I want is to run that method in a for loop, say ten times, and be shown each of the 10 positions that the circle is redrawn in every one second.

类似的东西:

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,但不知道如何使用它.而且睡眠功能不起作用.

I've read about QTimer, but do not know how to use it. And the sleep function does not work.

推荐答案

您需要做的就是从计时器事件中触发update(). update()方法在小部件上安排paintEvent.

All you need to do is to trigger an update() from the timer event. The update() method schedules a paintEvent on the widget.

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

It is invalid to paint on a widget outside of the paintEvent - that's the mistake that all other answers did at the time I posted this answer. Merely calling the paintEvent method is not a workaround. You should call update(). Calling repaint() would also work, but do so only when you have understood the difference from update() and have a very good reason for doing so.

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

这篇关于QT:如何每秒循环一个方法? C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:20