首页 > 解决方案 > 当Qt C++中有一个定时器时中断一个函数

问题描述

我正在尝试在 Qt 中制作一个程序。我不会发送所有,而是我有问题的片段。关键是,我必须中断一个包含 Timer 的函数,但我不知道如何在它在计时器之前等待时中断它。请回复!

void MainWindow::Test(){
    TestWrite();       //TestWrite is a function where I write my answer 
    QTimer::singleShot(5000, this, &MainWindow::TestCheck);     //TestCheck is a function where the answer is checked 
}
 
void MainWindow::on_Test_clicked()
{
    Test();
    timer = new QTimer(this);           //Creates a timer and calls the Test function every 7 seconds 

    timer->connect(timer, &QTimer::timeout, this, &MainWindow::Test);
    timer->start(7000);
}
 
........
........
 
void MainWindow::on_Back_clicked()
{
    timer->stop();   //I am trying to make the "Back" button interrupt the Test, TestWrite and TestCheck functions. Now, if you quickly click "Back" and "Test", the effect is as if you did not click the "Back" button 
}

标签: c++qttimerqtimer

解决方案


Qt 中从静态QTimer函数开始的定时器(就像你在 中所做的那样MainWindow::Test)根本无法停止,因为没有暴露给你的定时器对象可以用来stop()(或以其他方式操作)定时器。这样的计时器在任何情况下都会过期,并且在任何情况下它们都会发出信号。您需要在您的插槽中决定您是否仍然对信号感兴趣。

当您创建一个显式计时器对象时(就像您在 中所做的那样on_test_clicked(),您只能使用stop()它,或者start()用最短到期时间 (0) 重新设置它以使其“立即”到期。

如果您不想让已经启动的计时器过期,那就简单stop()了。

您提出问题的方式表明可能对 Qt 中计时器的工作方式存在误解。没有什么在“等待”定时器,而是一个过期的定时器向一个槽发送信号。Qt 中的“等待”会冻结您的用户界面。


推荐阅读