当程序在执行一项(或多项)耗时比较久的操作时,界面总要有一点东西告诉用户“程序还在运行中”,那么,一个“没有终点”的进度条就是你需要的了。
PS:最好把耗时的操作扔到一个子线程中去,以免他阻塞了界面线程,造成程序卡死的假象。
源代码:
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include "waitingdialog.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); WaitingDialog w; w.setWindowTitle("Please wait..."); QEventLoop *loop = new QEventLoop; w.Start(50, 150); w.show(); //开启一个事件循环,10秒后退出 QTimer::singleShot(10000, loop, SLOT(quit())); loop->exec(); return 0; } |
waitingdialog.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#ifndef WAITINGDIALOG_H #define WAITINGDIALOG_H #include <QDialog> #include <QProgressBar> #include <QTimer> 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(); }; #endif // WAITINGDIALOG_H |
waitingdialog.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
#include "waitingdialog.h" #include <QHBoxLayout> 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(); } |
发表评论
要发表评论,您必须先登录。