在mainwindow.ui
中,我創建了一個名爲的名稱爲progressBar
的名爲speckle
的QPushButton
,它開始大量計算。Qt - 如何爲QProgressBar結合使用QtConcurrent和QThreadPool?
在mainwindow.h
裏面,我有一個合適的private slot
爲按鈕和一個代表繁重計算的私有函數。 mainwindow.h
:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_speckle_clicked();
...
private:
Ui::MainWindow *ui;
QFutureWatcher<std::vector<cv::Mat>> futureWatcher;
std::vector<cv::Mat> progressSpecle();//heavy computation
};
的futureWatcher
應該手錶即會從QtConcurrent
返回的QFuture
對象:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
...
connect(&this->futureWatcher, SIGNAL(progressValueChanged(int)), ui->progressBar, SLOT(setValue(int)));
...
}
...
void MainWindow::on_speckle_clicked()
{
//Start the computation.
QFuture<std::vector<cv::Mat>> future;
future = QtConcurrent::run(this, &MainWindow::progressSpecle);
this->futureWatcher.setFuture(future);
QThreadPool::globalInstance()->waitForDone();
vector<cv::Mat> result = future.result();
specklevisualization *s = new specklevisualization;
s-> setAttribute(Qt::WA_DeleteOnClose);
s-> start(result);
s-> show();
}
但應用不喜歡的工作。在編輯並點擊斑點mainwindow
不響應。這裏是progressSpecle
成員函數,其中x線程被創建:在while(true)
的
void MainWindow::progressSpecle(){
vector<cv::Mat> input;
...//do something with input
vector<cv::Mat> result;
vector<cv::Mat> *all;
all = &result;
QThreadPool *threadPool = QThreadPool::globalInstance();
for(unsigned int i = 1; i<input.size(); i++) {
cv_speckle_algorithm *work = new cv_speckle_algorithm(input.at(i-1), input.at(i), all, i-1);
work->setAutoDelete(false);
threadPool->start(work);
}
while(true){
if(threadPool->activeThreadCount() == 1) return result;
}
}
應用工作沒有錯誤,但因爲(我認爲)的主窗口概不負責。但我不明白爲什麼這應該阻止mainWindow,因爲整個progressSpecle
函數在創建的單獨線程中工作,並以QtConcurrent
開始。
爲什麼progressSpecle
函數阻塞mainWindow? 那麼我怎樣才能讓progressBar
工作?
稍微偏離主題,但...如果'specklevisualization'以任何方式繼承'QWidget',那麼你不能在非GUI線程上創建它的一個實例。 –
@ G.M。我已經改變了'progressSpecle'函數,以便它返回'result'向量。 – goulashsoup
您是否在您的MainWindow構造函數之前創建了應用程序對象? QObject :: connect()是否向控制檯窗口輸出錯誤? – falkb