QProgressDialong是Qt提供的用于显示各类耗时较长的操作进度,而不至于让程序看上去假死了一样,它继承自QDialog。
下面给出例子:
QProgressDialog *progressDlg=new QProgressDialog(this);
//其实这一步就已经开始显示进度条了
progressDlg->setWindowModality(Qt::WindowModal);
progressDlg->setMinimumDuration(0);
progressDlg->setAttribute(Qt::WA_DeleteOnClose, true);
progressDlg->setWindowTitle(tr("上传文件"));
progressDlg->setLabelText(tr("正在上传......"));
progressDlg->setCancelButtonText(tr("取消"));
progressDlg->setRange(0,8000);
for(int i=1;i<8000;i++)
//注意这里是从1开始的
{
do something;
progressDlg->setValue(i);
if(progressDlg->wasCanceled())
{
do something;
}
}
progressDlg->close();
首先关于
progressDlg->setMinimumDuration(0);
但是在测试中会出现Dialog不显示,程序依旧进入假死状态,原因是QProgressDialog有一个智能延迟,默认一切短于4秒的操作都不显示Dialog,因为测试时的数据量往往很小,从而导致了问题。所以这里把这个值设为0,以最小的延迟显示进度条。
官方文档是这么说的:
A common problem with progress dialogs is that it is difficult to know when to use them; operations take different amounts of time on different hardware.QProgressDialog offers a solution to this problem: it estimates the time the operation will take (based on time for steps), and only shows itself if that estimate is beyondminimumDuration() (4 seconds by default).
然后是
progressDlg->setAttribute(Qt::WA_DeleteOnClose, true);
这个太重要了,有时候整个进度条会卡住,啥也不显示(一般是只显示一块白色的面板)然后就什么也动不了了
调用close()函数也关不掉。这时候 就需要progressDlg->setAttribute(Qt::WA_DeleteOnClose, true);
这样在调用Close的时候,窗口一定会被 关掉。至于具体的原因,因为对qt的框架不太熟悉,所以不是太懂。
QProgressDialog *progressDlg=new QProgressDialog(this); //其实这一步就已经开始显示进度条了progressDlg->setWindowModality(Qt::WindowModal);progressDlg->setMinimumDuration(0);progressDlg->setAttribute(Qt::WA_DeleteOnClose, true);progressDlg->setWindowTitle(tr("上传文件"));progressDlg->setLabelText(tr("正在上传......"));progressDlg->setCancelButtonText(tr("取消"));progressDlg->setRange(0,8000);for(int i=1;i<8000;i++) //注意这里是从1开始的{do something;progressDlg->setValue(i);if(progressDlg->wasCanceled()){do something;}}progressDlg->close();