简体   繁体   English

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

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

As a self-learner, I am trying to understand QThread logics in c++ with QT .作为一个自学者,我试图用QT理解 C++ 中的QThread逻辑。 I wrote simple thread class which has for loop inside.我写了一个简单的线程类,里面有 for 循环。 However when thread is inside for loop I cannot use MainWindow.但是,当线程在 for 循环内时,我无法使用 MainWindow。 To try it I open QFileDialog and select some files.为了尝试它,我打开QFileDialog并选择一些文件。 When I press " Open " button thread runs and FileDialog is not closing until thread finish his job.当我按下“ Open ”按钮时,线程运行并且FileDialog在线程完成他的工作之前不会关闭。

Is it possible to use MainWindow while thread is working background?线程在后台工作时是否可以使用 MainWindow?

Here is simple code for my try..这是我尝试的简单代码..

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;
    }
}

You shouldn't wait() on the thread in your click handler!您不应该在单击处理程序中的线程上wait() Also, you don't call a thread's run yourself, you just start the thread.此外,您不会自己调用线程的run ,您只需启动线程。 Starting the thread will call run() .启动线程将调用run()

This is a minimal example of using a thread for code that blocks.这是将线程用于阻塞代码的最小示例。 The main thread remains interactive and outputs tick... every second until the thread is done.主线程保持交互并输出tick...每秒,直到线程完成。 When the tread is finished, it cleanly quits.当胎面完成时,它干净地退出。

While I demonstrate a console application, this could just as easily be a GUI application and the GUI thread would not be blocked at any point.虽然我演示了一个控制台应用程序,但它也可以很容易地成为一个 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