一、前言
项目中在下发指令时,结果异步返回,可能需要一段时间,因此需要用到加载动画。
用的比较简单,就是新建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();
}