日志
Qt的进度条实现
2012-03-31 12:17
// progressbar.h
#ifndef PROGRESSBAR_H #define PROGRESSBAR_H #include <QDialog> class QLabel; class QLineEdit; class QComboBox; class QPushButton; class QProgressBar; class Progress : public QDialog { Q_OBJECT public: Progress(QWidget *parent=0,Qt::WindowFlags f=0); ~Progress(); private: QLabel *numLabel; QLineEdit *numLineEdit; QLabel *typeLabel; QComboBox *typeComboBox; QProgressBar *progressBar; QPushButton *startPushButton; private slots: void slotStart(); }; #endif // PROGRESSBAR_H #include "progressbar.h" #include <QLabel> #include <QLineEdit> #include <QComboBox> #include <QProgressBar> #include <QPushButton> #include <QGridLayout> #include <QProgressDialog> #include <QApplication> #include <QTest> //以便调用QTest::qSleep(); 实现延时功能 Progress::Progress(QWidget *parent,Qt::WindowFlags f):QDialog(parent,f) { QFont font("Times", 10, QFont::Bold); setFont(font); setWindowTitle("ProgressBar"); numLabel=new QLabel("File Num:"); numLineEdit=new QLineEdit; numLineEdit->setText("10"); typeLabel=new QLabel("Progress Type:"); typeComboBox=new QComboBox; typeComboBox->addItem("ProgressBar"); typeComboBox->addItem("ProgressDialog"); progressBar=new QProgressBar; startPushButton=new QPushButton("Start"); QGridLayout *layout=new QGridLayout; layout->addWidget(numLabel,0,0); layout->addWidget(numLineEdit,0,1); layout->addWidget(typeLabel,1,0); layout->addWidget(typeComboBox,1,1); layout->addWidget(progressBar,2,0,1,2); layout->addWidget(startPushButton,3,1); layout->setMargin(15); // 布局外边框的宽度 layout->setSpacing(10); //部件间的间距 setLayout(layout); connect(startPushButton,SIGNAL(clicked()),this,SLOT(slotStart())); } Progress::~Progress(){} void Progress::slotStart() { int num=numLineEdit->text().toInt(); if (typeComboBox->currentIndex()==0) { progressBar->setRange(0,num); for (int i=0;i<num;i++) { progressBar->setValue(i+1); // 注意,这里是i+1,不是i,这样才能显示100% QTest::qSleep(100); } } else if (typeComboBox->currentIndex()==1) { QProgressDialog *progressDialog=new QProgressDialog(this); QFont font("Times", 10, QFont::Bold); 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=0;i<num;i++) { progressDialog->setValue(i+1); // 注意,这里是i+1,不是i,这样才能显示100% qApp->processEvents(); //来正常相应时间循环,以确保应用程序不会出现阻塞。 QTest::qSleep(100); if (progressDialog->wasCanceled()) return; } } } 这个程序只是个实例,模拟文件的复制过程,这里用到了延时函数qSleep(),它包含于QTest类中,在使用它之前,首先要在pro文件中加入:CONFIG +=qtestlib注意,在加入上述声明后,运行程序以后会弹出cmd窗口,这个是正常的,QTest用来测试,默认就带cmd黑色窗口,我一开不了解,四处找去掉的原因,在实际运用过程中,我们不需要QTest类,只需要将实际的文件复制代码覆盖程序中的QTest::qSleep(100);即可... |
下一篇: QT 一些非常常用的操作
上一篇: Qt之实现360安全卫士主界面(一)