[英]Multi-thread not working in QT
I'm developing C++ application in QT with GUI. 我正在使用GUI在QT中开发C ++应用程序。 To make the GUI always respond, I create a thread for other blocking process.
为了使GUI始终响应,我为其他阻止进程创建了一个线程。 However, the application is waiting for the blocking process and therefore the GUI didn't respond.
但是,该应用程序正在等待阻止过程,因此GUI没有响应。 Is creating a thread for blocking process is a wrong way?
创建用于阻塞进程的线程是错误的方法吗? Or it doesn't work in QT?
还是在QT中不起作用? If so, how to make the GUI respond?
如果是这样,如何使GUI响应? Please give me example.
请举个例子。
This is a simple example of multithreaded application with responsive GUI: 这是带有响应式GUI的多线程应用程序的简单示例:
main.cpp 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: 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 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. Qt具有很好的多线程支持。 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!
有很多方法可以实现“响应式” GUI! (Including a lot of ways how to implement another thread!)
(包括很多方法如何实现另一个线程!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.