简体   繁体   English

如何使用 QThread 创建一个分离的线程,就像在 std::thread 中一样

[英]how to create a detached thread with QThread, like in std::thread

i've created a thread in QT using QThread but the parent of the thread is exiting before the thread finishes which itself is running infifnitely.我已经使用 QThread 在 QT 中创建了一个线程,但是线程的父线程在线程完成之前退出,而线程本身正在无限运行。

//mainwindow.cpp
void MainWindow::showEvent(QShowEvent *ev)
{
    QMainWindow::showEvent(ev);
    showEventHelper();
}

void MainWindow::showEventHelper()
{
    //back-end thread

    ServerStart *serverstart = new ServerStart();//initializing a pointer to my class
    QThread thread;
    serverstart->moveToThread(&thread);
    QObject::connect(&thread, &QThread::started, serverstart, &ServerStart::run);
    thread.start();

    //in std::thread i used to detache it like so:
    //std::thread worker(serverMain);
    //worker.detach();
}

IMPORTANT: I'm making a GUI project.重要提示:我正在制作一个 GUI 项目。 and my infinite thread is inside an onShow() method that needs to exit in order for the app to continue and make the UI.我的无限线程在一个 onShow() 方法中,该方法需要退出才能让应用程序继续并制作 UI。 and I also want to send signals in the future from the thread to the main thread and the main thread should be able to respond and modify the UI according to the signal.而且我也想以后从线程向主线程发送信号,主线程应该能够根据信号响应和修改UI。

how can i do the same in QT?我如何在 QT 中做同样的事情?

您不能,但是根据正确QThread使用的 KDAB 文档,您可以通过将QThread::finished连接到QThead::deleteLater来模拟这种行为,如他们的QThread文档所示https://www.kdab.com/wp-内容/上传/故事/multithreading-with-qt-1.pdf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM