繁体   English   中英

线程在 QT 中工作时如何使用 GUI?

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

作为一个自学者,我试图用QT理解 C++ 中的QThread逻辑。 我写了一个简单的线程类,里面有 for 循环。 但是,当线程在 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();
}

暂无
暂无

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

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