QT显示加载动画


一、前言

项目中在下发指令时,结果异步返回,可能需要一段时间,因此需要用到加载动画。
用的比较简单,就是新建Widget子窗口,放一个Label,使用QMovie在Label中播放GIF。
当下发指令时,就打开子窗口显示加载过程,同时开启一个定时器,如果在定时器触发超时信号或超时之前收到结果,则隐藏加载过程子窗口,并关闭定时器。

二、使用

1.FormLoading.h

#ifndef FORMLOADING_H
#define FORMLOADING_H

#include <QWidget>
#include <QMovie>
#include <QLabel>

namespace Ui {
class FormLoading;
}

class FormLoading : public QWidget
{
    Q_OBJECT

public:
    explicit FormLoading(QWidget *parent = 0);
    ~FormLoading();
    void startAnimation();
    void stopAnimation();

protected:
    void paintEvent(QPaintEvent *p1);

private:
    Ui::FormLoading *ui;
    QMovie *m_pMovie;
    QLabel *m_pLabel;
};

#endif // FORMLOADING_H

2.FormLoading.cpp

#include "formloading.h"
#include "ui_formloading.h"
#include <QVBoxLayout>
#include <QPainter>
#include <QBitmap>
FormLoading::FormLoading(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormLoading)
{
    ui->setupUi(this);
    // 设置窗口置顶和无边框
    this->setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
    // 设置窗口透明用来支持圆角样式属性
    this->setAttribute(Qt::WA_TranslucentBackground);
    // 设置模态对话框
    this->setWindowModality(Qt::ApplicationModal);

    setFixedSize(350, 280);
    m_pMovie = new QMovie(":/images/loading.gif");
    m_pLabel = new QLabel(this);
    m_pLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    // 设置背景透明
    m_pLabel->setAutoFillBackground(true);
    //m_pLabel->setStyleSheet("width:150px;border-radius:10px; background-color: rgb(255, 255, 255);");
    m_pLabel->setStyleSheet("background-color: rgba(255, 255, 255, 0);");
    m_pLabel->setMovie(m_pMovie);
    QVBoxLayout *pLayout = new QVBoxLayout(this);
    pLayout->addWidget(m_pLabel);
    setLayout(pLayout);
}

FormLoading::~FormLoading()
{
    delete ui;
    if(m_pMovie != nullptr)
    {
        delete m_pMovie;
    }

    if(m_pLabel != nullptr)
    {
        delete m_pLabel;
    }
}

// 绘图事件
void FormLoading::paintEvent(QPaintEvent *p1)
{
    //绘制样式
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);//绘制样式

    QBitmap bmp(this->size());
    bmp.fill();
    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.drawRoundedRect(bmp.rect(), 15, 15);
    setMask(bmp);
}

void FormLoading::startAnimation()
{
    m_pMovie->start();
}

void FormLoading::stopAnimation()
{
    m_pMovie->stop();
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值