QProgressBar类的几个重要属性:
- minimum:进度条指示的最小值;
- maximum:进度条指示的最大值;
- format:决定进度条显示文字的格式,可以有三种显示格式:"%p%"(显示完成的百分比,默认显示方式)、"%v"(显示当前的进度值)和"%m"(显示总的步进值);
设置进度条的步进范围:
QProgressBar::setRange(0, 10000);
QProgressDialog类的几个重要属性:
mininum:进度条最小值;
maximum:进度条最大值;
minimumDuration:进度条对话框出现的等待时间,若小于设定的等待时间(minimumDuration)则不出现进度条对话框;
步进值百分比计算公式:
百分比=(value() - minimum()) / (maximum() - minimum())
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QProgressBar>
#include <QComboBox>
#include <QPushButton>
#include <QGridLayout>
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = nullptr);
~Dialog();
private slots:
void startProgress();
private:
QLabel *FileNum;
QLineEdit *FileNumLineEdit;
QLabel *ProgressType;
QComboBox *comboBox;
QProgressBar *progressBar;
QPushButton *starBtn;
QGridLayout *mainLayout;
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include <QProgressDialog>
#include <QFont>
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
QFont font("ZYSong18030", 12);
setFont(font);
setWindowTitle("Progress");
FileNum = new QLabel();
FileNum->setText("文件数目: ");
FileNumLineEdit = new QLineEdit();
FileNumLineEdit->setText("200000");
ProgressType = new QLabel();
ProgressType->setText("显示类型: ");
comboBox = new QComboBox();
comboBox->addItem("progressBar");
comboBox->addItem("progressDialog");
progressBar = new QProgressBar();
starBtn = new QPushButton();
starBtn->setText("开始");
mainLayout = new QGridLayout(this);
mainLayout->addWidget(FileNum, 0, 0);
mainLayout->addWidget(FileNumLineEdit, 0, 1);
mainLayout->addWidget(ProgressType, 1, 0);
mainLayout->addWidget(comboBox, 1, 1);
mainLayout->addWidget(progressBar, 2, 0, 1, 2);
mainLayout->addWidget(starBtn, 3, 1);
mainLayout->setMargin(15);
mainLayout->setSpacing(10);
connect(starBtn, SIGNAL(clicked()), this, SLOT(startProgress()));
}
Dialog::~Dialog()
{
}
void Dialog::startProgress()
{
bool ok;
int num = FileNumLineEdit->text().toInt(&ok);
if(comboBox->currentIndex() == 0) {
progressBar->setRange(0, num);
for(int i=1; i<num+1; i++) {
progressBar->setValue(i);
}
} else if (comboBox->currentIndex() == 1) {
QProgressDialog *progressDialog = new QProgressDialog(this);
QFont font("ZYSong18030", 12);
progressDialog->setFont(font);
progressDialog->setWindowModality(Qt::WindowModal);
progressDialog->setMinimumDuration(5);
progressDialog->setWindowTitle("Please Wait");
progressDialog->setLabelText("Copying...");
progressDialog->setCancelButtonText("Cancel");
progressDialog->setRange(0, num);
for (int i=1; i<num+1; i++) {
progressDialog->setValue(i);
if (progressDialog->wasCanceled()) {
qDebug("Progress Dialog Was Canceled!");
return;
}
}
}
}
main.cpp
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}