Qt带进度条的启动界面

        通过继承QSplashScreen类,得到CMySplashScreen类,然后在CMySplashScreen中定义QProgressBar变量,该变量以CMySplashScreen为父类,这样就实现了带进度条的启动界面。

        进度条加入后,需要控制进度条的值,为了让进度条看起来更逼真,可以通过生成随机数的方式,把随机数当做进度条的值。此时,生成的随机数必须是从小到大排列的,要不然进度条就不会从开端一步步走到终点,而是会出现走到一半后又回到开端等反常现象。如何生成随机数可参考http://blog.csdn.net/caoshangpa/article/details/51036267

        CMySplashScreen类的实现如下所示。

#ifndef CMYSPLASHSCREEN_H
#define CMYSPLASHSCREEN_H

#include <QSplashScreen>
#include <QPixmap>
#include <QProgressBar>
#include <QList>
#include <QtGlobal>

class CMySplashScreen: public QSplashScreen
{
     Q_OBJECT

public:
     CMySplashScreen(QPixmap& pixmap,int time);
     ~CMySplashScreen();

private:
     //进度条
     QProgressBar *ProgressBar;
     //随机数列表
     QList<int> numbersList;
     //启动界面停留的时间
     int elapseTime;

private:
     void setProgress();
     void generateAscendRandomNumber();

private slots:    
     void slotUpdateProgress();
};

#endif // CMYSPLASHSCREEN_H


#include "cmysplashscreen.h"
#include <QTime>
#include <QTimer>
CMySplashScreen::CMySplashScreen(QPixmap& pixmap,int time) :
    QSplashScreen(pixmap),
    elapseTime(time)
{
    ProgressBar = new QProgressBar(this);
    //设置进度条的位置
    ProgressBar->setGeometry(0,pixmap.height()-50,pixmap.width(),30);
    //设置进度条的样式
    ProgressBar->setStyleSheet("QProgressBar {color:black;font:30px;text-align:center; }QProgressBar::chunk {background-color: rgb(202, 165, 14);}");
    //设置进度条的样式
    ProgressBar->setRange(0, 100);
    //设置进度条的当前进度
    ProgressBar->setValue(0);

    generateAscendRandomNumber();
    setProgress();
}

CMySplashScreen::~CMySplashScreen()
{

}

void CMySplashScreen::setProgress()
{
    int tempTime=elapseTime/100;
    for(int i=0;i<100;i++)
    {
       QTimer::singleShot(i*tempTime, this, SLOT(slotUpdateProgress()));
    }
    QTimer::singleShot(elapseTime, this, SLOT(close()));
}

void CMySplashScreen::slotUpdateProgress()
{
    static int num=0;
    ProgressBar->setValue(numbersList[num]);
    num++;
}

void CMySplashScreen::generateAscendRandomNumber()
{
    int i;
    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
    //生成100个大小在[0,100]之间的随机数
    for(i=0;i<100;i++)
    {
        numbersList.append(qrand()%101);
    }
    //递增排序
    qSort(numbersList.begin(),numbersList.end());
}

启动界面效果如下所示。

Qt带进度条的启动界面_第1张图片
源码链接:见http://blog.csdn.net/caoshangpa/article/details/51037427的评论

你可能感兴趣的:(Qt带进度条的启动界面)