简体   繁体   中英

Multi-thread not working in QT

I'm developing C++ application in QT with GUI. To make the GUI always respond, I create a thread for other blocking process. However, the application is waiting for the blocking process and therefore the GUI didn't respond. Is creating a thread for blocking process is a wrong way? Or it doesn't work in QT? If so, how to make the GUI respond? Please give me example.

This is a simple example of multithreaded application with responsive GUI:

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QPushButton>
#include <QLineEdit>
#include <QThread>

class Worker : public QThread
{
protected:
    /// Wait 3s which simulates time demanding job.
    void run() { sleep(3); }
};

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);

public slots:
    void doJob(bool);
    void jobFinished();

private:
    Worker worker;
    QLineEdit *line;
    QPushButton *button;
    int counter;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include <QVBoxLayout>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      line(new QLineEdit()),
      button(new QPushButton()),
      counter(0)
{
    line->setDisabled(true);
    line->setAlignment(Qt::AlignRight);
    line->setText(QString::number(counter));
    button->setText("Push");

    connect(button, SIGNAL(clicked(bool)), this, SLOT(doJob(bool)));
    connect(&worker, SIGNAL(finished()), this, SLOT(jobFinished()));

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(line);
    layout->addWidget(button);
    QWidget *window = new QWidget();
    window->setLayout(layout);
    setCentralWidget(window);
}    

void MainWindow::doJob(bool)
{
    // Only one thread is running at a time.
    // If you want a thread pool, the implementation is up to you :)
    worker.start();

    // Uncomment to wait. If waiting, GUI is not responsive.
    //worker.wait();
}

void MainWindow::jobFinished()
{
    ++counter;
    line->setText(QString::number(counter));
}

Qt has a very good multithreading support. You probably do something wrong and we can't help you if you don't provide any code. There are a lot of ways of implementing "responsive" GUI! (Including a lot of ways how to implement another thread!)

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