当我执行这个Qtimer时,它说“在非成员函数中无效使用'this'”
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()函数属于同一个类。我想要做的是在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时,iT无法正常工作
答案 0 :(得分:1)
将QTimer声明为您班级的成员
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;
}
在约束器中启动计时器对象
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();
}