Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

c++ - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...