Search code examples
c++qtqtimer

how to stop the Qtimer upon a condition


when i executing this Qtimer it says "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;
}

my ball.h file

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

the move() function is in the same class. what i want to do is stop the returned timer upon a if condition is satisfied.

when i issue this code in Ball::Ball constructor in Cpp it works fine. the ball is moving.

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

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

  timer->start(15);

but when i add Qtimer *timerStart beyond the Ball::Ball constructor, iT doesnt work


Solution

  • Declare the QTimer as a member in you class

    h file:

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

    Initiate the timer object in your constractor

    cpp file:

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