考虑一下SLOT
,在我的主线程中,由一个按钮触发,该按钮QTreeWidgetItem
从QTreeWidget
. 它使用QtConcurrent::map()
调用来执行一个长任务。watcher
连接到 a以显示QProgressDialog
进度。
void Main::on_actionButton_triggered() {
qRegisterMetaType<QVector<int> >("QVector<int>");
//Setting up a progress dialog
QProgressDialog progressDialog;
//Holds the list
QList<QTreeWidgetItem*> list;
//Setup watcher
QFutureWatcher<void> watcher;
//Setting up connections
//Progress dialog
connect(&watcher, SIGNAL(progressValueChanged(int)), &progressDialog, SLOT(setValue(int)));
connect(&watcher, SIGNAL(progressRangeChanged(int, int)), &progressDialog, SLOT(setRange(int,int)));
connect(&watcher, SIGNAL(progressValueChanged(int)), ui->progressBar, SLOT(setValue(int)));
connect(&watcher, SIGNAL(progressRangeChanged(int, int)), ui->progressBar, SLOT(setRange(int,int)));
connect(&watcher, SIGNAL(finished()), &progressDialog, SLOT(reset()));
connect(&progressDialog, SIGNAL(canceled()), &watcher, SLOT(cancel()));
connect(&watcher, SIGNAL(started()), this, SLOT(processStarted()));
connect(&watcher, SIGNAL(finished()), this, SLOT(processFinished()));
//Gets the list filled
for (int i = 0; i < ui->listTreeWidget->topLevelItemCount(); i++) {
list.append(ui->listTreeWidget->topLevelItem(i));
}
//And start
watcher.setFuture(QtConcurrent::map(list, processRoutine));
//Show the dialog
progressDialog.exec();
}
extern void processRoutine(QTreeWidgetItem* item) {
qDebug() << item->text(4);
}
我还在 UI(包含所有以前的小部件)中添加了QProgressBar
具有相同 SIGNALS/SLOTS 的 a。保持与之前一样的代码按预期工作:显示进度对话框,并且进度条完全按照对话框更新。相反,如果我评论
//progressDialog.exec();
或者我以某种方式隐藏对话框,进程崩溃(并非总是如此,有时它运行良好)。看着qDebug() << item->text(4);
它崩溃,输出显示随机混合的文本(它们应该是文件名)。QProgressDialog
此外,即使计算没有崩溃,进度条也不会在未显示时自行更新。
注意:我之前在另一个函数中遇到过类似的问题,我通过设置解决了它
QThreadPool::globalInstance()->setMaxThreadCount(1);
仅在 Windows 上,OSX 没问题。
那么,QProgressDialog
使所有事情都正确的背后的诀窍是什么?有没有办法我可以使用QProgressBar
而不是QProgressDialog
?
笔记
这是该过程顺利完成时的输出:
"C:/Users/Utente/Pictures/Originals/unsplash_52cee67a5c618_1.jpg"
"C:/Users/Utente/Pictures/Originals/photo-1428278953961-a8bc45e05f72.jpg"
"C:/Users/Utente/Pictures/Originals/photo-1429152937938-07b5f2828cdd.jpg"
"C:/Users/Utente/Pictures/Originals/photo-1429277158984-614d155e0017.jpg"
"C:/Users/Utente/Pictures/Originals/photo-1430598825529-927d770c194f.jpg"
"C:/Users/Utente/Pictures/Originals/photo-1433838552652-f9a46b332c40.jpg"