Progress.pro
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = Progress
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += main.cpp \
progressdlg.cpp
HEADERS += progressdlg.h
main.cpp
#include "progressdlg.h"
#include <QApplication>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
ProgressDlg w;
w.show();
return a.exec();
}
progressdlg.h
#ifndef PROGRESSDLG_H
#define PROGRESSDLG_H
#include <QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QProgressBar>
#include <QComboBox>
#include <QPushButton>
#include <QGridLayout>
#include <QFont>
class ProgressDlg : public QDialog {
Q_OBJECT
public:
explicit ProgressDlg(QWidget *parent = 0);
private slots:
void startProgress();
private:
QFont font;
QLabel *FileNum;
QLineEdit *FileNumLineEdit;
QLabel *ProgressType;
QComboBox *comboBox;
QProgressBar *progressBar;
QPushButton *starBtn;
QGridLayout *mainLayout;
};
#endif // PROGRESSDLG_H
progressdlg.cpp
#include "progressdlg.h"
#include <QProgressDialog>
#include <QTimer>
ProgressDlg::ProgressDlg(QWidget *parent) : QDialog(parent) {
font.setFamily("ZYSong18030");
font.setPointSize(12);
setFont(font);
setWindowFlags(Qt::WindowCloseButtonHint);
setWindowTitle(tr("Progress"));
FileNum =new QLabel(tr("文件数目:"));
FileNumLineEdit =new QLineEdit(tr("100000"));
ProgressType = new QLabel(tr("显示类型:"));
comboBox = new QComboBox;
comboBox->addItem(tr("progressBar"));
comboBox->addItem(tr("progressDialog"));
progressBar = new QProgressBar;
starBtn = new QPushButton(tr("开始"));
connect(starBtn, SIGNAL(clicked()), this, SLOT(startProgress()), Qt::UniqueConnection);
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);
}
void ProgressDlg::startProgress() {
bool ok;
int num = FileNumLineEdit->text().toInt(&ok);
if(ok) {
starBtn->setEnabled(false);
if(comboBox->currentIndex() == 0) { //采用进度条的方式显示进度
progressBar->setRange(0, num);
for(int i=1; i<num+1; i++) {
progressBar->setValue(i);
}
progressBar->reset();
} else if(comboBox->currentIndex() == 1) { //采用进度对话框显示进度
//创建一个进度对话框
QProgressDialog *progressDialog = new QProgressDialog(this);
progressDialog->setFont(font);
progressDialog->setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint);
progressDialog->setWindowModality(Qt::WindowModal);
progressDialog->setMinimumDuration(5);
progressDialog->setWindowTitle(tr("Please Wait"));
progressDialog->setLabelText(tr("Copying..."));
progressDialog->setCancelButtonText(tr("Cancel"));
progressDialog->setRange(0, num);//设置进度对话框的步进范围
for(int i=1; i<num+1; i++) {
progressDialog->setValue(i);
if(progressDialog->wasCanceled())
return;
}
}
//防止按钮快速重复点击
QTimer::singleShot(1000, this, [=]{starBtn->setEnabled(true);});
}
}