在QT创建者中停止QTIMER

stopping a qtimer in Qt creator

本文关键字:QTIMER QT 创建者      更新时间:2023-10-16

我在这样的主构造函数中设置了qtimer。

Ball::Ball(QGraphicsItem *parent): QGraphicsRectItem(parent), QObject(){
    // draw rect
    setRect(0,0,50,50);
    QBrush brush;
    brush.setStyle(Qt::SolidPattern);
    brush.setColor(Qt::red);
    setBrush(brush);
    // move up right initially
    xVelocity = 0;
    yVelocity = -5;

    QTimer* timer = new QTimer();
    connect(timer,SIGNAL(timeout()),this,SLOT(move()));
    timer->start(15);
}

定时执行计时器中的MOVE()fution。

void Ball::move(){
    reverseVelocityIfOutOfBounds();
    handlePaddleCollision();
    handleBlockCollision();
    moveBy(xVelocity,yVelocity);
}

在上述reversevelocityifoutofbounds();功能,有这样的条件。

// bottom edge - NONE (can fall through bottom)
if (mapToScene(rect().topRight()).y() >= screenH){

执行此操作后,我想停止QTimer。我应用了一切。但是该程序一直意外地关闭。请任何帮助都将受到高度应用。

您可以做的最简单的事情是使计时器成为球类的成员变量。然后,您有一个句柄,只需在reversevelocityIfoutofBounds()中调用Timer-> stop()。

您可以做的另一件事是调用sender()移动以获取计时器对象并将其传递给reversevelocityifoutofbounds(虽然不良样式),却不能跨线程。