當程序在執行一項(或多項)耗時比較久的操作時,界面總要有一點東西告訴用戶“程序還在運行中”,那么,一個“沒有終點”的進度條就是你需要的了。
PS:最好把耗時的操作扔到一個子線程中去,以免他阻塞了界面線程,造成程序卡死的假象。
思路:程序很簡單,一個進度條,一個定時器就足夠了。
截圖:
源代碼:
- #include <QtCore>
- #include <QtGui>
- class WaitingDialog : public QDialog
- {
- Q_OBJECT
- private:
- int m_CurrentValue; //當前值
- int m_UpdateInterval; //更新間隔
- int m_MaxValue; //最大值
- QTimer m_Timer;
- QProgressBar *m_ProgressBar;
- public:
- WaitingDialog(QWidget *parent = 0);
- ~WaitingDialog();
- void Start(int interval=100, int maxValue=100);
- void Stop();
- private slots:
- void UpdateSlot();
- };
- WaitingDialog::WaitingDialog(QWidget *parent)
- {
- m_ProgressBar = new QProgressBar(this);
- m_CurrentValue = m_MaxValue = m_UpdateInterval = 0;
- m_ProgressBar->setRange(0, 100);
- connect(&m_Timer, SIGNAL(timeout()), this, SLOT(UpdateSlot()));
- m_ProgressBar->setTextVisible(false);
- QHBoxLayout *layout = new QHBoxLayout;
- layout->addWidget(m_ProgressBar);
- setLayout(layout);
- }
- WaitingDialog::~WaitingDialog()
- {
- }
- void WaitingDialog::UpdateSlot()
- {
- m_CurrentValue++;
- if( m_CurrentValue == m_MaxValue )
- m_CurrentValue = 0;
- m_ProgressBar->setValue(m_CurrentValue);
- }
- void WaitingDialog::Start(int interval/* =100 */, int maxValue/* =100 */)
- {
- m_UpdateInterval = interval;
- m_MaxValue = maxValue;
- m_Timer.start(m_UpdateInterval);
- m_ProgressBar->setRange(0, m_MaxValue);
- m_ProgressBar->setValue(0);
- }
- void WaitingDialog::Stop()
- {
- m_Timer.stop();
- }
- #include "main.moc"
- int main(int argc, char **argv)
- {
- QApplication app(argc, argv);
- WaitingDialog *dialog = new WaitingDialog;
- dialog->setWindowTitle("Please wait...");
- QEventLoop *loop = new QEventLoop;
- dialog->Start(50, 150),
- dialog->show();
- //開啟一個事件循環,10秒后退出
- QTimer::singleShot(10000, loop, SLOT(quit()));
- loop->exec();
- return 0;
- }
http://blog.csdn.net/small_qch/article/details/7664634