2015-12-29 52 views
1

我一直試圖在我的application中使用QThread來處理大型數據。它的作品,但它不完美,並在鏈接上的當前版本崩潰我的應用程序。我讀了一些地方(不能找到鏈接)來使用QTimer和信號和插槽。用於處理大型數組的QTimer

我想要做的是能遍歷:

connect(this, &UsersProcess::ProgressBarSetValue, this->progressBar, &QProgressBar::setValue); 

... 
int maxRows = this->listUsers->size(); 
for(auto iter = this->listUsers->begin(); iter != this->listUsers->end(); ++iter) 
{ 
    row++; 
    emit this->ProgressBarSetValue(row); 
} 

,其中信號ProgressBarSetValue更新QProgressBar值。我不確定要做什麼是把它放在QTimer中,這樣它不會導致MainWindow在循環結束之前不可用。

想知道是否有人可以給我一個想法或文章如何做到這一點。或者如果沒有使用QThread有其他的替代方案。

+0

的可能的複製[QT進度條顯示功能的狀態] (http://stackoverflow.com/questions/22551978/qt-progress-bar-showing-status-of-a-function) – user2672165

回答

1

查看QtConcurrent庫。 QtConcurrent :: run可能對你有所幫助。

例子。 在userprocess.h:

class UserProcess : public QMainWindow 
{ 
    Q_OBJECT 

public: 
.............. 
    void setValue(int Value); 

signals: 
    void ProgreeBarSetValue(int Value); 

private: 
    Ui::UserProcess *ui; 
    QStringList _data; 
}; 

在的.cpp你定義了這個功能:

void doWork(UserProcess* process, const QStringList &list) 
{ 
    static int row = 0; 
    for(auto iter = list.begin(); iter != list.end(); ++iter) 
    { 
     ++row; 
     process->setValue(row); 
     QThread::msleep(1); //just slows up this function 
    } 
} 

然後你讓你使用Qt連接:QueuedConnection標誌:

connect(this, &UserProcess::ProgreeBarSetValue, ui->progressBar, &QProgressBar::setValue, Qt::QueuedConnection); 

添加一些隨機數據到我們的清單

for(int i = 0; i < 1000; ++i) 
     _data.append(QString::number(i)); 

ui->progressBar->setMaximum(1000); 

void UserProcess::setValue(int Value) 
{ 
    emit ProgreeBarSetValue(Value); 
} 

開始我們的辛勤功能

QtConcurrent::run(doWork, this, _data); 

而且不要忘記在.pro文件中添加此

QT += concurrent