问如何实现流程循环

Qt how to implement a process loop?

本文关键字:程循环 循环 实现 何实现      更新时间:2023-10-16

我刚开始使用Qt,目前正在调整一个命令行程序,使其与GUI一起使用。

我正在构建这样的GUI:

int main(int argc, char *argv[])    
{    
    QApplication a(argc, argv);    
    MainWindow w;    
    w.show();    
    return a.exec();    
}    

我想永久处理一些事件。在命令行中,我使用了while循环,它工作得很好。使用Qt,我不知道如何正确处理这些事件。所以我尝试使用std::线程,但当我尝试从线程修改GUI时,我的Qt应用程序崩溃了。使用QThread也有同样的问题。我不需要线程,所以如果我能把我的代码放在Qt的主线程中,那就太好了。

有人能帮我吗?

您可以使用连接到MainWindow类中插槽的QTimer来周期性地运行一个函数,如下所示:

MainWindow::MainWindow()
{
    myTimer = new QTimer();
    myTimer->setSingleShot(false);
    myTimer->start(intervalInMilliseconds);
    connect(myTimer, &QTimer::timeout, this, &MainWindow::handleMyEvents);
}
void MainWindow::handleMyEvents()
{
    // Your code here
}

您也可以使用线程,但请注意,您不能从任何非QApplication线程的线程调用任何GUI代码,这可能是您的尝试失败的原因。