Qt笔记(四十六)之Qt设置启动动画(3)图片+进度条

104 篇文章 122 订阅

一.前言
设置软件启动动画,前面分别讲述了
单纯设置图片和倒计时: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();

效果:
在这里插入图片描述

  • 1
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值