我需要在另一个线程中运行计算量大的函数,以便GUI在运行时不会冻结或变灰。
我遵循以下示例:https : //stackoverflow.com/a/16501374/2904614
但是GUI仍然冻结并变成灰色。
MainWindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->textBrowser->setFont(QFont("Monospace",11));
ui->textBrowser->setLineWrapMode(QTextEdit::NoWrap);
updater->moveToThread(thread);
connect(updater,SIGNAL(req()), this, SLOT(getCheckSum()));
connect(thread, SIGNAL(destroyed()), updater, SLOT(deleteLater()));
thread->start();
}
用户单击指定的按钮时。由于一个目录中可能有很多文件,因此QDirIterator遍历所有文件时,GUI会冻结。我希望添加一个进度条,该进度条将向用户显示程序仍在运行。
void MainWindow::on_pushButton_clicked()
{
updater->getHash();
//getCheckSum();
}
编辑我想让函数MainWindow::getCheckSum()
在不同于GUI的线程中运行。我将如何实施?
GitHub:https : //github.com/Jyang772/PenguSniff
鉴于您只需要运行一个功能,我建议您使用QtConcurrent。提取文档:
在单独的线程中运行函数
要在另一个线程中运行一个函数,请使用QtConcurrent :: run():
extern void aFunction();
QFuture<void> future = QtConcurrent::run(aFunction);
这将在从默认QThreadPool获得的单独线程中运行aFunction。您可以使用QFuture和QFutureWatcher类来监视函数的状态。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句