[英]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.