c++ - 当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
}
解决方案
Qt 中从静态QTimer
函数开始的定时器(就像你在 中所做的那样MainWindow::Test
)根本无法停止,因为没有暴露给你的定时器对象可以用来stop()
(或以其他方式操作)定时器。这样的计时器在任何情况下都会过期,并且在任何情况下它们都会发出信号。您需要在您的插槽中决定您是否仍然对信号感兴趣。
当您创建一个显式计时器对象时(就像您在 中所做的那样on_test_clicked()
,您只能使用stop()
它,或者start()
用最短到期时间 (0) 重新设置它以使其“立即”到期。
如果您不想让已经启动的计时器过期,那就简单stop()
了。
您提出问题的方式表明可能对 Qt 中计时器的工作方式存在误解。没有什么在“等待”定时器,而是一个过期的定时器向一个槽发送信号。Qt 中的“等待”会冻结您的用户界面。
推荐阅读
- c# - 在 Web Api .Net 中路由重定向 URL
- arrays - 从实时数据库firebase中获取数据以反应本机?
- python-3.x - 不断获取 mysql.connector :找到未读结果
- java - 在 AndroidX 中不推荐使用 setUserVisibleHint 时加载数据
- node.js - 即使 IP 设置正确,我的 heroku 应用程序仍会崩溃
- windows - 如何引发 WerFault.exe
- algorithm - 找到组成多边形的矩形联合的轮廓
- javascript - 使用 Hooks 将类组件转换为功能组件
- amazon-s3 - AWS CloudFront 和失效延迟导致重复按需调整图像大小
- javascript - 提供具有列出字段的类型