[QT] Customize the startup page with a progress bar

1. Function and Demonstration

Set the startup page to load data, initialization and other operations before the software starts, and display the loading progress

 Second, the source code

SplashScreen.h
#ifndef SPLASHSCREEN_H
#define SPLASHSCREEN_H

#include <QProgressBar>
#include <QSplashScreen>

class SplashScreen : public QSplashScreen
{
    Q_OBJECT

public:
    SplashScreen(const QPixmap &pixmap);
    ~SplashScreen();
    void setRange(int minimum, int maximum);
    void setMinimum(int minimum);
    void setMaximum(int maximum);
    void setValue(int value);
    void showProgressMessage(int value, const QString &message);

protected:
    void drawContents(QPainter *painter);

private:
    QProgressBar *m_progressBar;
};

#endif // SPLASHSCREEN_H
SplashScreen.cpp
#include "SplashScreen.h"
#include <QPainter>

SplashScreen::SplashScreen(const QPixmap &pixmap)
    : QSplashScreen(pixmap)
{
    m_progressBar = new QProgressBar(this);
    m_progressBar->setGeometry(20, pixmap.height() - 30, pixmap.width() * 0.95, 20);
    m_progressBar->setStyleSheet(
        "QProgressBar{"
        "height:22px;"
        "text-align:center;"
        "font-size:14px;"
        "color:white; "
        "border-radius:11px;"
        "background: #1D5573;}"

        "QProgressBar::chunk{"
        "border-radius:11px;"
        "background:qlineargradient(spread:pad,x1:0,y1:0,x2:1,y2:0,stop:0 #01FAFF,stop:1  #26B4FF);"
        "}"
    );
}

SplashScreen::~SplashScreen()
{

}

void SplashScreen::setRange(int minimum, int maximum)
{
    m_progressBar->setRange(minimum, maximum);
}

void SplashScreen::setMinimum(int minimum)
{
    m_progressBar->setMinimum(minimum);
}

void SplashScreen::setMaximum(int maximum)
{
    m_progressBar->setMaximum(maximum);
}

void SplashScreen::setValue(int value)
{
    m_progressBar->setValue(value);
}

void SplashScreen::showProgressMessage(int value, const QString &message)
{
    setValue(value);
    showMessage(message, Qt::AlignLeft, Qt::red);
}

void SplashScreen::drawContents(QPainter *painter)
{
    painter->setFont(QFont("Helvetica", 12, QFont::Bold));
    QSplashScreen::drawContents(painter);
}

How to use

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

    //SplashScreen
    QPixmap pixmap(":/config/images/loading_page.png");
    SplashScreen splash(pixmap.scaled(800, 460, Qt::KeepAspectRatio));
    splash.setRange(0, 5);
    splash.show();
    splash.showProgressMessage(1, QCoreApplication::tr("Load config file"));

    splash.showProgressMessage(2, QCoreApplication::tr("Robot init"));

    Util::delayMsec(500);
    app.processEvents();

    MainWindow w;
    w.show();

    splash.finish(&w);
    return app.exec();
}

Guess you like

Origin blog.csdn.net/qq_40602000/article/details/122291852