c++ - 如何设置时间延迟以触发 Qt 中即将发生的事件

标签 c++ qt qt5

我将使用时间延迟来触发一个事件。一旦一个进程完成,就会发出一个信号,例如,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/

相关文章:

c++ - 立即使用 boost::asio 检测写入期间关闭的 TCP 连接

c++ - 使用多个字符串定界符拆分字符串

python - 使用 QWebView 显示 PDF 文件

c++ - QByteArray 到 Integer 的转换产生不正确的结果

python - Qt - 自定义窗口 Chrome

c++ - 在函数声明中,传递一个固定大小的数组意味着什么?

c++ - 在 Windows 上工作,但在 Ubuntu 上出现段错误

c++ - QDoubleValidator 接受多个小数点

python - 没有名为 PyQt5.sip 的模块

c++ - 简单的 Qt 应用程序无法在 Mac OSX Yosemite 上打开