Qt Example 7: Draw a multi-colored car speedometer with Qt

The following is a sample code for a colored progress bar implemented using Qt:

#include <QApplication>
#include <QWidget>
#include <QProgressBar>
#include <QTimer>
int main(int argc, char *argv[])
{
    
    
    QApplication app(argc, argv);
    QWidget *window = new QWidget;
    window->setWindowTitle("Colorful Progress Bar");
    QProgressBar *progressBar = new QProgressBar(window);
    progressBar->setGeometry(30, 30, 200, 25);
    progressBar->setRange(0, 100);
    progressBar->setTextVisible(false);
    QTimer *timer = new QTimer(window);
    QObject::connect(timer, &QTimer::timeout, [=]() {
    
    
        static int value = 0;
        value = (value + 1) % 101;
        progressBar->setValue(value);
        if (value <= 33) {
    
    
            progressBar->setStyleSheet("QProgressBar { background-color: #FF0000; } QProgressBar::chunk { background-color: #FFD700; }");
        } else if (value <= 66) {
    
    
            progressBar->setStyleSheet("QProgressBar { background-color: #00FF00; } QProgressBar::chunk { background-color: #FF00D7; }");
        } else {
    
    
            progressBar->setStyleSheet("QProgressBar { background-color: #0000FF; } QProgressBar::chunk { background-color: #00FF00; }");
        }
    });
    timer->start(10);
    window->resize(260, 100);
    window->show();
    return app.exec();
}

This sample code implements a colored progress bar, and the color of the progress bar changes as the progress changes. In the implementation process, use the QProgressBar::chunk pseudo-state to set the color of the progress bar, use QTimer to simulate the change of the progress and update the display of the progress bar. By adjusting the style sheet of the progress bar, a more colorful progress bar effect can be achieved.

The effect is as follows:
insert image description here

Guess you like

Origin blog.csdn.net/dica54dica/article/details/130332063