线程在QT中执行任务时如何使用GUI

How to use GUI while threads doing their jobs in QT?

本文关键字:何使用 GUI 执行任务 QT 线程      更新时间:2023-10-16

作为一名自学者,我正在尝试用QT理解c++中的QThread逻辑。我写了一个简单的线程类,里面有for循环。然而,当线程在循环内部时,我不能使用MainWindow。为了尝试它,我打开QFileDialog并选择一些文件。当我按下"Open"按钮时,线程运行,FileDialog不会关闭,直到线程完成他的工作。

线程在后台工作时,是否可以使用MainWindow?

这是我尝试的简单代码。。

void MainWindow::on_pushButton_clicked()
{
    QFileDialog *lFileDialog = new QFileDialog(this, "Select Folder", "/.1/Projects/", "*");
    QStringList selectedFileNames = lFileDialog->getOpenFileNames(this, "Select Images", "/home/mg/Desktop/", "", 0, 0);
    if(!selectedFileNames.isEmpty())
    {
        MyThread mThread1;
        mThread1.name = "thread1";
        mThread1.run();
        mThread1.wait();
    }
}

void MyThread::run()
{
    for (int var = 0; var < 100000; ++var)
    {
        qDebug() << this->name << var;
    }
}

您不应该在单击处理程序的线程上wait()!此外,您不需要自己调用线程的run,只需启动线程即可。启动线程将调用run()

这是一个将线程用于阻塞代码的最小示例。主线程保持交互,并每秒输出tick...,直到线程完成为止。当踏面完成时,它会干净地退出。

当我演示控制台应用程序时,它可以很容易地成为GUI应用程序,并且GUI线程在任何时候都不会被阻塞。

#include <QCoreApplication>
#include <QThread>
#include <QTimer>
#include <QTextStream>
#include <cstdio>
class MyThread : public QThread {
  void run() Q_DECL_OVERRIDE {
    sleep(10); // block for 10 seconds
  }
public:
  MyThread(QObject * parent = 0) : QThread(parent) {}
  ~MyThread() {
    wait(); // important: It's illegal to destruct a running thread!
  }
}
int main(int argc, char ** argv) {
  QCoreApplication app(argc, argv);
  QTextStream out(stdout);
  MyThread thread;
  QTimer timer;
  timer.start(1000);
  QObject::connect(&timer, &QTimer::timeout, [&out]{
    out << "tick..." << endl;
  }
  app.connect(&thread, SIGNAL(finished()), SLOT(quit()));
  thread.start();
  return app.exec();
}