19

我有一个带有这种 main() 的 Qt 应用程序...

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow   mainWin;

    ... A separate, non-GUI thread is launched here

    mainWin.Init();
    mainWin.show();

    app.exec();
}

在 mainWin 之前创建的另一个线程需要知道它何时可以开始与 mainWin 通信。但是由于 mainWin 使用 Qt 信号、槽、计时器等,它并没有真正准备好直到事件循环运行(通过 exec())。

我的问题是:事件循环开始时是否会发出一些信号或事件?

考虑一下。在 mainWin.Init() 中,您可以创建类似 QTimer 的东西,甚至可以调用 .start() 来启动它。但在调用 exec() 之前,它实际上不会运行并触发事件。这就是为什么我需要知道事件循环何时真正开始。

4

3 回答 3

15

exec()您可以在通话前向您的窗口发送信号。app这将在的信号队列中放置一个条目。运行时exec(),将传递信号,您的窗口将知道事件循环正在运行。

一种简单的方法是使用QTimer::singleShot(0, &mainWin, SLOT(onEventLoopStarted()));which 连接到您的窗口类的自定义插槽。

于 2012-01-16T09:32:15.157 回答
2

由于在事件循环尚未运行时发出的信号不会丢失,因此您的线程可能不一定需要知道您的窗口何时准备就绪。
您的线程可以立即开始向窗口发送信号但它只会在事件循环运行时从窗口接收信号。

于 2012-01-16T09:44:51.343 回答
1

您可以按以下顺序执行此操作:

QApplication app(argc, argv);
Mainwinwdow mainWin;
QThread yourThread;

//connect the signals from the thread to the mainWin here

mainWin.Init();
mainWin.show();

yourThread.start();

return app.exec();
于 2012-01-16T09:03:39.493 回答