【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_;
    //结束样例
}

 

你可能感兴趣的:(C++,Qt,Qt,progressbar)