简体   繁体   中英

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 . I wrote simple thread class which has for loop inside. However when thread is inside for loop I cannot use MainWindow. To try it I open QFileDialog and select some files. When I press " Open " button thread runs and FileDialog is not closing until thread finish his job.

Is it possible to use MainWindow while thread is working background?

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! Also, you don't call a thread's run yourself, you just start the thread. Starting the thread will call 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. 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.

#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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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