可以使用Qt提供的QProgressBar类来手动创建进度条控件,并通过 QTimer 类的定时器来更新进度值。
示例代码如下:
#include <QProgressBar>
#include <QTimer>
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = nullptr) : QWidget(parent)
{
progressBar = new QProgressBar(this);
progressBar->setMinimum(0);
progressBar->setMaximum(100);
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &MyWidget::updateProgress);
timer->start(1000); // 定时器每秒触发timeout信号
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(progressBar);
setLayout(layout);
}
private:
QProgressBar *progressBar;
QTimer *timer;
int progressValue = 0;
private slots:
void updateProgress()
{
if (progressValue > 100)
{
progressValue = 0;
}
progressBar->setValue(progressValue++);
}
};
以上代码创建了一个继承自QWidget的MyWidget类,该类有一个QProgressBar成员变量和一个QTimer成员变量,以及一个updateProgress函数。在构造函数中,设置了进度条的最小值和最大值,启动了定时器并将进度条添加到布局中。在updateProgress函数中,如果当前进度值超过了最大值,则重置为最小值,然后通过setValue函数更新进度条的进度值。每隔一秒钟就会触发一次定时器,进而更新进度条的进度值。
使用该控件只需要在主程序中创建MyWidget对象即可:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyWidget w;
w.show();
return a.exec();
}