我将使用时间延迟来触发一个事件。一旦一个进程完成,就会发出一个信号,例如,mysignal(int timedelay)
,信号的接收者将在指定时间的一段时间内恰好启动另一个进程timedelay
在信号发出后经过。
是否有一些专门的功能来处理这个问题?我注意到 QThread::sleep()
或 QThread::msleep()
可能适合处理这种情况?它们是否比使用 QTimer 对象并相应地设置信号槽连接更好?
最佳答案
不要在 Qt 事件循环所在的主线程上使用 QThread::sleep()
,因为它会阻塞信号、事件等。而是使用调用其任务的函数的 QTimer就是发出信号。
例子:
#include <QtCore>
class Sender: public QObject
{
Q_OBJECT
public:
using QObject::QObject;
Q_SIGNAL void mysignal(const QString & text);
void process(){
/**
* process
*/
int timeout = 1000;
// send signal after 1000 ms
QTimer::singleShot(timeout, this, &Sender::send_signal);
}
private:
// The only task of this function is to emit the signal
void send_signal(){
qDebug()<< "send signal";
Q_EMIT mysignal("Hello");
}
};
class Receiver: public QObject
{
Q_OBJECT
public:
using QObject::QObject;
Q_SLOT void myslot(const QString & text){
qDebug()<< "Received:" << text;
QCoreApplication::quit();
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Sender sender;
Receiver receiver;
QObject::connect(&sender, &Sender::mysignal, &receiver, &Receiver::myslot);
// call process
QTimer::singleShot(1000, &sender, &Sender::process);
return a.exec();
}
#include "main.moc"
关于c++ - 如何设置时间延迟以触发 Qt 中即将发生的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55154764/