QT进度条设计。 - 创建进度条 - 建立按钮控件(初始信息为start) - 点击按钮控件,按钮控件信息为stop,进度条变动进度。 - 再次点击按钮空间,按钮控件信息为start,进度条停止 - 进度条更新完成,按钮控件显示finished
时间: 2024-02-25 18:56:40 浏览: 33
下面是一个使用Qt Widgets创建进度条和按钮的示例程序:
```cpp
#include <QProgressBar>
#include <QPushButton>
#include <QVBoxLayout>
#include <QTimer>
class ProgressBar : public QWidget
{
public:
ProgressBar(QWidget *parent = nullptr) : QWidget(parent)
{
// 创建进度条和按钮控件
progress_bar = new QProgressBar;
progress_bar->setRange(0, 100);
button = new QPushButton("Start");
// 建立布局
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(progress_bar);
layout->addWidget(button);
setLayout(layout);
// 创建计时器
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &ProgressBar::on_timeout);
// 进度条默认停止
progress_bar->setValue(0);
button->setText("Start");
// 连接按钮的点击事件
connect(button, &QPushButton::clicked, this, &ProgressBar::on_button_click);
}
private slots:
void on_button_click()
{
if (timer->isActive()) {
// 如果计时器在运行,停止计时器,停止进度条更新
timer->stop();
progress_bar->setValue(0);
button->setText("Start");
} else {
// 否则,启动计时器,开始更新进度条
timer->start(100);
button->setText("Stop");
}
}
void on_timeout()
{
// 进度条更新
int value = progress_bar->value() + 1;
if (value > 100) {
// 进度条更新完成,停止计时器,按钮控件信息显示finished
timer->stop();
button->setText("Finished");
} else {
progress_bar->setValue(value);
}
}
private:
QProgressBar *progress_bar;
QPushButton *button;
QTimer *timer;
};
```
在这个示例程序中,我们创建了一个ProgressBar类,继承自QWidget。在ProgressBar类的构造函数中,我们创建了一个QProgressBar和一个QPushButton控件,并将它们添加到一个QVBoxLayout布局中。我们还创建了一个QTimer计时器,用于每100毫秒更新进度条。在on_button_click方法中,我们检查计时器是否处于活动状态,并根据情况启动或停止计时器。在on_timeout方法中,我们检查进度条的值是否达到100。如果是,我们停止计时器,并将按钮控件信息显示为finished。否则,我们将进度条的值增加1。
此外,我们使用了setRange方法来设置进度条的最小和最大值。你可以根据需要调整这些值。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)