如何减慢标签上的打印进度值?

Tha*_*Cao 3 c++ qt multithreading sleep progress-bar

我使用标签打印 0 到 100 作为 Qt C++ 进度条的一部分。我使用下面的代码来执行此操作,但执行速度太快:

for (i = 0; i <= 100; i++)
{
    data = QString::number(i);
    ui->label_29->setText(data + "%");
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用sleep()函数,但它冻结了exe文件并且无法运行。我正在考虑使用线程,但我不知道如何使用。

Par*_*H.R 6

要在每个步骤之间延迟更新进度条而不冻结 GUI,您可以利用 Qt 的 QTimer 类来安排定期更新。

这是一个例子:

#include <QApplication>
#include <QLabel>
#include <QTimer>

class ProgressBarExample : public QObject
{
    Q_OBJECT

public:
    ProgressBarExample() : i(0)
    {
        // Create and configure the label
        label = new QLabel();
        label->setAlignment(Qt::AlignCenter);
        label->setFixedSize(200, 30);

        // Create the QTimer object and connect its timeout signal to the updateProgressBar slot
        timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &ProgressBarExample::updateProgressBar);

        // Set the desired interval (in milliseconds) between updates
        int interval = 100; // Adjust this value as per your requirement
        timer->setInterval(interval);

        // Start the timer
        timer->start();

        // Show the label
        label->show();
    }

private slots:
    void updateProgressBar()
    {
        if (i > 100) {
            // Stop the timer if the progress reaches 100%
            timer->stop();
            return;
        }

        QString data = QString::number(i);
        label->setText(data + "%");

        i++; // Increment the counter
    }

private:
    QLabel* label;
    QTimer* timer;
    int i;
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    ProgressBarExample example;

    return app.exec();
}

#include "main.moc"


Run Code Online (Sandbox Code Playgroud)