我希望在progressBar上显示函数的进度。按照指南,我编写了下面的代码。但在函数执行期间,程序冻结,然后进度条的值变为1。
程序本身不会产生错误。函数的结果是正确的。
我想我的问题是我不知道如何将函数的进度值与进度条的值联系起来。
(Form.h)
public:
MyObject object;
QFutureWatcher<QBitArray> FutureWatcher;
QFuture<QBitArray> future;(Form.cpp)表单构造函数主体:
ui->setupUi(this);
ui->progressBar->setMinimum(0);
ui->progressBar->setMaximum(100);
connect(&this->FutureWatcher, SIGNAL(progressValueChanged(int)), ui->progressBar, SLOT(setValue(int)));(Form.cpp)函数on_button_clicked():
void Form::on_button_clicked()
{
QString message = ui->textEdit->toPlainText();
future = QtConcurrent::run(&this->object, &MyObject::longFunction, message);
this->FutureWatcher.setFuture(future);
QBitArray bitresult = future.result();
}发布于 2020-07-05 03:36:50
问题是您立即调用了future.result()。这样做的问题是,result()会一直等到QFuture完成。
Qt文档说(https://doc.qt.io/qt-5/qfuture.html#result):
如果结果不能立即可用,此函数将阻塞并等待结果变为可用。
解决方案是将插槽连接到QFutureWatcher::finished()
auto *watcher = new QFutureWatcher<QBitArray>(this);
connect(watcher, &QFutureWatcher::finished, this, [=]() {
auto result = watcher->result();
// do something with the result
// important: delete watcher again
watcher->deleteLater();
});
// now start the task
QString message = ui->textEdit->toPlainText();
watcher->setFuture(QtConcurrent::run(myObject, &MyObject::longFunction, message));https://stackoverflow.com/questions/62727466
复制相似问题