一.前言
设置软件启动动画,前面分别讲述了
单纯设置图片和倒计时:Qt笔记(四十六)之Qt设置启动动画(1)
显示gif图片:Qt笔记(四十六)之Qt设置启动动画(2)
上述两种方式就不太能给用户直观的时长感觉,最直观的还是进度条方式,从用户角度来说,知道还需要等多久,不会有漫无目的的等下去的感觉。楼主就启动动画图片+进度条做一个分享记录
二.实现过程
1.基本思路
核心还是使用QSplashScreen,这个是Qt提供的启动动画封装类,另外单纯的QSplashScreen又没有提供进度条的功能,又要用原先的功能,又要加上进度条,很自然就是需要用到继承了
2.核心代码
.h文件
#ifndef SPLASHSCREEN_H
#define SPLASHSCREEN_H
#include <QObject>
#include <QSplashScreen>
#include <QPixmap>
#include <QWidget>
#include <QProgressBar>
#include <QTime>
#include <QCoreApplication>
class SplashScreen : public QSplashScreen
{
public:
explicit SplashScreen(QPixmap pixmap,QWidget *parent=0);
~SplashScreen(){}
public:
void setRange(int min,int max);
void mySleep(int ms);
public slots:
void updateNum(int n);
protected:
bool eventFilter(QObject *watched, QEvent *event);
private:
QProgressBar *progressBar;
};
#endif // SPLASHSCREEN_H
.cpp文件
#include "SplashScreen.h"
#include <QDebug>
SplashScreen::SplashScreen(QPixmap pixmap,QWidget *parent):
QSplashScreen(parent,pixmap)
{
installEventFilter(this);
progressBar = new QProgressBar(this);
progressBar->setAlignment(Qt::AlignCenter);
// 设置进度条的位置
progressBar->setGeometry(0,pixmap.height()/2,pixmap.width(),30);
}
void SplashScreen::setRange(int min,int max)
{
progressBar->setRange(min,max);
}
void SplashScreen::updateNum(int n)
{
qDebug()<<n;
// 延迟凸显效果
mySleep(500);
progressBar->setValue(n);
}
void SplashScreen::mySleep(int ms)
{
QTime time = QTime::currentTime().addMSecs(ms);
while (QTime::currentTime()<time) {
QCoreApplication::processEvents(QEventLoop::AllEvents,100);
}
}
bool SplashScreen::eventFilter(QObject *watched, QEvent *event)
{
// 使用事件过滤器,防止进度条在加载中的时候,用户点击了图片,造成窗口被隐藏
// 可以去除体验效果
if(event->type()==QEvent::Type::MouseButtonPress || event->type()==QEvent::Type::MouseButtonDblClick)
{
return true;
}
return false;
}
main.cpp中使用
QPixmap pixmap("://loading.png");
SplashScreen sp(pixmap);
sp.setRange(0,10);
sp.show();
int i=0;
while(i<=10){
sp.updateNum(i);
i++;
}
Widget widget;
sp.finish(&widget);
widget.show();
效果: