QT 进度条类 QProgressDialog的简单使用

一、The QProgressDialog class provides feedback on the progress of a slow operation. 

QProgressDialog 类对于比较慢的处理进程提供了一种反馈,使得我们在进行操作的时候能够看到处理的进度。例如:

二、打开Qt,新建项目,名称为new4,选择Widget,这里不用Mainwindow,ui设计很简单,拖放一个按钮即可:

三、在Pushbutton右键选择“转到槽”,我们这里利用计时器,每秒设置一次进度值。所以除了包含QProgressDialog外,还需要包含QTimer。定义一个perform()函数用来设置进度值。头文件定义如下:

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QProgressDialog>
#include <QTimer>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private slots:
    void on_pushButton_clicked();
    void perform();

private:
    Ui::Widget *ui;

    QProgressDialog *pd;
    QTimer *t;
};

#endif // WIDGET_H

四、cpp文件如下:

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{
    //新建对象,参数含义:对话框正文,取消按钮名称,进度条范围
    pd = new QProgressDialog("正在保存...","取消",0,100,this);
    //模态对话框
    pd->setWindowModality(Qt::WindowModal);
    //如果进度条运行的时间小于5,进度条就不会显示,默认是4S
    pd->setMinimumDuration(5);
    //设置标题
    pd->setWindowTitle("请稍后");
    //显示处理框
    pd->show();
    //处理过程。。。
    t = new QTimer(this);
    connect(t, SIGNAL(timeout()), this, SLOT(perform()));
    t->start(1000);
}

int steps = 0;

void Widget::perform()
{
    steps++;
    pd->setValue(steps);
    if(steps > pd->maximum() || pd->wasCanceled())
    {
        t->stop();
        steps = 0;
        delete pd;
    }

}

五、运行效果见第一步。点击取消的时候或者步长超过最大值,计时器机会停止,同时对变量重新赋值为0,最后删除定义的对象。再次点击按钮,计时器打开,进度依然从头开始。
 

参考文献:https://www.cnblogs.com/etwd/p/4521862.html

猜你喜欢

转载自blog.csdn.net/HB_Programmer/article/details/81099535