也许我正在重新发明轮子,我想知道一切是否正确(也许在我的实现中没有考虑到所有事情),或者它可以更好、更简单吗?
有一个函数MainWindow::someSlot,其中某个部分 ( MainWindow::veryLongFunc) 必须在单独的线程中完成,以便接口不会挂起。
#mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
int otherFields() const;
void setOtherFields(int otherFields);
public slots:
void someSlot();
private:
void veryLongFunc();
Ui::MainWindow *ui;
int _otherFields;
};
#endif // MAINWINDOW_H
主窗口.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtConcurrent>
#include <future>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
}
void MainWindow::someSlot() {
/* some code */
QFuture<void> t = QtConcurrent::run([this] { veryLongFunc(); });
while(!t.isFinished()) {
QApplication::processEvents();
}
/* some code */
}
void MainWindow::veryLongFunc() {
/* very long func */
}
int MainWindow::otherFields() const
{
return _otherFields;
}
void MainWindow::setOtherFields(int otherFields)
{
_otherFields = otherFields;
}
MainWindow::~MainWindow() { delete ui; }
不要
while(!t.isFinished()) {}- 您正在拖延应用程序的主线程(及其整个 GUI),直到函数线程完成其工作。正如我在评论中指出的那样,您需要使用 QFutureWatcher 类,它会在线程中的函数完成执行时向我们发出信号。
获取一个类对象
QFutureWatcher в MainWindow:在 MainWindow 构造函数中:
更远:
这样您就可以避免在运行非常长的函数时 GUI 没有响应。