如何根据条件停止 Qtimer

how to stop the Qtimer upon a condition

当我执行这个 Qtimer 时它说 "invalid use of 'this' in non-member function"

QTimer *timerStart( )
{
QTimer* timer = new QTimer(  );
Ball *b = new Ball();

QObject::connect(timer,SIGNAL(timeout()),b,SLOT(move()));
//timer->start( timeMillisecond );
timer->start(15);
return timer;
}

我的ball.h文件

class Ball: public QObject, public QGraphicsRectItem{
Q_OBJECT
public:
// constructors
Ball(QGraphicsItem* parent=NULL);

// public methods
double getCenterX();




public slots:
// public slots
void move();



private:
// private attributes
double xVelocity;
double yVelocity;
int counter = 0;
QTimer timerStart( );



// private methods
void stop();
void resetState();
void reverseVelocityIfOutOfBounds();
void handlePaddleCollision();
void handleBlockCollision();
};

#endif // BALL_H

move() 函数在同一个 class 中。我想做的是在满足 if 条件时停止返回的计时器。

当我在 Cpp 的 Ball::Ball 构造函数中发出此代码时,它工作正常。球在移动。

  QTimer* timer = new QTimer();
  timer->setInterval(4000);

  connect(timer,SIGNAL(timeout()),this,SLOT(move()));

  timer->start(15);

但是当我在 Ball::Ball 构造函数之外添加 Qtimer *timerStart 时,它不起作用

将 QTimer 声明为您的成员 class

h 文件:

class Ball: public QObject, public QGraphicsRectItem{
{
  Q_OBJECT

  public:
    // constructor
    Ball(QGraphicsItem* parent=Q_NULLPTR);
    // control your timer
    void start();
    void stop();
    ...
  private:
    QTimer * m_poTimer;
}

在您的构造函数中启动定时器对象

cpp 文件:

Ball::Ball(QGraphicsItem* parent) :
      QGraphicsItem(parent)
{  
  m_poTimer = new QTimer(this); // add this as a parent to control the timer resource
  m_poTimer->setInterval(4000);

  connect(m_poTimer,SIGNAL(timeout()),this,SLOT(move()));
}

void Ball::start()
{
   // start timer
   m_poTimer->start();
}

void Ball::stop()
{
   // stop timer
   m_poTimer->stop();
}