void wait() const{ QEventLoop waiter; QTimer timer; auto wait = [&]() { waiter.quit(); }; QObject::connect(&timer, &QTimer::timeout, this, wait); timer.start(1000); waiter.exec();}
class Async : public QObject{ Q_OBJECTpublic: explicit Async(std::function<void()> callback, QObject* parent = nullptr) : QObject(parent) , m_callback(callback) { } void runAsync() { thread()->msleep(500); if (m_callback) m_callback(); }private: std::function<void()> m_callback;};class Waiter : public QObject{Q_OBJECTpublic:void wait() const{ QEventLoop waiter; auto wait = [&]() { waiter.quit(); }; Async async(wait); QtConcurrent::run(&async, &Async::runAsync); waiter.exec();}};
C++ (Qt)class CWaitLoop : public QEventLoop{ Q_OBJECTpublic: explicit CWaitLoop(QObject *parent = nullptr) : QEventLoop(parent) {} int wait(int msecs); public slots: void exitSlot(int code) { QEventLoop::exit(code); }}; int CWaitLoop::wait(int msecs){ QTimer timer; timer.setSingleShot(true); timer.start(msecs); connect(&timer, &QTimer::timeout, this, &CWaitLoop::quit); return exec();} class AnyClass {...signals: void stopWaiting(int);}; ... AnyClass any; CWaitLoop waitLoop; connect(&any, &AnyClass::stopWaiting, &waitLoop, &CWaitLoop::exitSlot); int ret = waitLoop.wait(1000);