
在 Qt 中,你可以使用 QTimer 类来设定延迟执行某段代码。QTimer 允许你设置一个时间间隔,在时间间隔到达后触发一个信号槽机制来执行特定的代码。以下是一个示例,展示如何设定一段代码延迟 5 秒后执行:
#include <QCoreApplication>
#include <QTimer>
#include <QDebug>
class MyObject : public QObject
{
Q_OBJECT
public slots:
void delayedFunction() {
qDebug() << "This function is executed after 5 seconds.";
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyObject obj;
QTimer timer;
// Connect the timeout signal of QTimer to the slot we want to execute
QObject::connect(&timer, &QTimer::timeout, &obj, &MyObject::delayedFunction);
// Start the timer for 5000 milliseconds (5 seconds)
timer.start(5000);
return a.exec();
}
#include "main.moc"
在这个示例中:
- 我们定义了一个
MyObject类,其中包含一个槽函数delayedFunction,这个函数将在延迟时间到达后被调用。 - 在
main函数中,我们创建了一个QCoreApplication对象来管理应用程序的事件循环。 - 我们创建了
MyObject和QTimer对象。 - 使用
QObject::connect函数将QTimer的timeout信号连接到MyObject的delayedFunction槽。 - 调用
timer.start(5000)来启动定时器,设定延迟时间为 5000 毫秒(即 5 秒)。 - 调用
a.exec()来启动应用程序的事件循环,等待定时器超时事件。
当定时器超时(5 秒后),QTimer 会发出 timeout 信号,这个信号会触发 MyObject 的 delayedFunction 槽,从而执行延迟的代码。
Qt中代码延迟执行示例
847

被折叠的 条评论
为什么被折叠?



