【Qt】多線程控制多個進度條

一個線程控制一個進度條,通過信號和槽機制控制。

/*顯示進度條的Class: ShowWidget.cpp*/

for(int i = 0; i < size; i++)
{
	//......
	
	
	progress_bars_.append(new QProgressBar(this));
	progress_bars_[i]->setMinimum(0);
	progress_bars_[i]->setMaximum(100);
	progress_bars_[i]->setValue(0);
	progress_bars_[i]->setFormat(QString("當前進度爲:%1%").arg(0));

	progress_threads_.append(new QThread());
	update_percent_.append(new UpdatePercent(progress_bars_.at(i)));
	update_percent_.at(i)->moveToThread(progress_threads_.at(i));
	update_percent_.at(i)->setDir(data_path_);
	update_percent_.at(i)->setCarName(car_names_.at(i));
	connect(progress_threads_.at(i), SIGNAL(finished()), progress_threads_.at(i), SLOT(deleteLater()));
	connect(progress_threads_.at(i), SIGNAL(finished()), update_percent_.at(i), SLOT(deleteLater()));

    //此處爲更新進度條的信號和槽連接
	connect(update_percent_.at(i), SIGNAL(getprogressvalue(QProgressBar *, int)), this, SLOT(setprogressvalue(QProgressBar *, int)));
	progress_threads_.at(i)->start();
	update_percent_.at(i)->showpercent();

	//......
}

void ShowWidget::setprogressvalue(QProgressBar *mbar, int value){
    //qDebug() << "value = " << value;
    mbar->setValue(value);
    double dProgress = (mbar->value() - mbar->minimum()) * 100.0
            / (mbar->maximum() - mbar->minimum());
    mbar->setFormat(QString("當前進度爲:%1%").arg(QString::number(dProgress, 'd', 1)));
}

自己定義的class:用於發送信號,實時更新進度條的數值

/*UpdatePercent.cpp*/

//初始化子類進度條
pdatePercent::UpdatePercent(QProgressBar *bar) : pro_bar_(bar){
}

void UpdatePercent::clientFunc(){

    //此部分爲自己需要的功能
    //通過發送信號來更新進度條,即調用:
    //emit getprogressvalue(pro_bar_, value_);
    //emit getprogressvalue([子類進度條], [更新的百分比]);


    //樣例:以下是做了一個根據文件寫入的字節數控制的進度條更新
    int i;
    for(i = 0; i < fileInfoList.count(); i++)
    {
        QFileInfo fileInfo = fileInfoList.at(i);
        if (fileInfo.fileName() == "." || fileInfo.fileName() == ".." || fileInfo.isDir()) {
            continue;
        }
        if (fileInfo.fileName().indexOf(car_name_) != -1){
            qint64 file_size = fileInfo.size();
            if (file_size >= total_size_){
                value_ = 100;
            }
            else{
                float res = file_size / (float)total_size_ * 100;
                //qDebug() << "res:" << res;
                value_ = floor(file_size / (float)total_size_ * 100);
            }
            emit getprogressvalue(pro_bar_, value_);
            break;
        }
    }
    if (i == fileInfoList.count())
    {
        emit getprogressvalue(pro_bar_, 0);
    }
    //結束樣例

}


void UpdatePercent::showpercent()
{
    //根據自己需要功能選擇調用的入口函數
    //......

    //樣例:每一秒刷新一次進度條
    query_timer_ = new QTimer();
    connect(query_timer_, SIGNAL(timeout()), this, SLOT(clientFunc()));
    query_timer_->start(1000);
    qDebug() << "value_ = " << value_;
    //結束樣例
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章