windows 关闭时 QTimer 不停止

QTimer dont stop when windows is closed

我目前正在开始使用 QTCreator。我被要求在特定上下文中使用 QTimers,这是这样的:

我们有空 window, 一个或多个 QTimer 被触发,并使内容每隔 x 毫秒出现在屏幕上。 当我们按下“Escape”时,window 应该关闭并且所有内容都应该重置为 0.

但问题来了,定时器是以静态方式定义的:

QTimer::singleShot(500, this, SLOT(foo());

当我调用 this->close()(关闭我的 window)时,计时器不会停止并继续。我尝试了几种解决方案:浏览我的对象中包含的所有 QTimers,显然有 none 因为它们是在静态中定义的。我没有在静态中声明它们,而是尝试每次都创建一个新的 QTimer 对象:

    QTimer *timer= new QTimer(this);
    timer->setSingleShot(true);
    timer->setInterval(2000);
    timer->setParent(this);
    timer->start();

然后稍后调用 timer->stop(),但我认为当您在同一代码中有多个计时器时,这非常残酷。

有没有办法在调用 this->close 时停止定时器,知道定时器被定义为静态定时器?

假设您正在使用,

QWindow *qw = new QWindow();
QTimer *timer= new QTimer(); 

要解决这个问题,您需要将 QWindow 的 destroyed() 信号连接到计时器的插槽 stop() 因此,一旦 window 被销毁,所有已注册的计时器将在没有显式停止调用的情况下停止。确保连接所有计时器实例。代码片段如下,

QObject::connect(&qw, SIGNAL(destroyed()), timer, SLOT(stop()))
QObject::connect(&qw, SIGNAL(destroyed()), timer2, SLOT(stop()))
QObject::connect(&qw, SIGNAL(destroyed()), timer3, SLOT(stop()))

PS:

QTimer *timer= new QTimer(this); // here you are setting parent as 'this' already
timer->setSingleShot(true);
timer->setInterval(2000);
timer->setParent(this); // remove this, no need to set parent again.
timer->start();