Qt耗时操作添加动画等待加载效果

前言

本例模拟耗时请求实现动画等待加载效果,采用QtConcurrent::run实现异步耗时操作,通过QFutureWatcher异步监测耗时操作结果的返回值做相应的动画演示。


一、第一种自定义动态加载类

第一种自定义动画等待加载类QProgressIndicator

1.QProgressIndicator.h

#ifndef QPROGRESSINDICATOR_H
#define QPROGRESSINDICATOR_H

#include <QWidget>
#include <QColor>

/*!
    \class QProgressIndicator
    \brief The QProgressIndicator class lets an application display a progress indicator to show that a lengthy task is under way.

    Progress indicators are indeterminate and do nothing more than spin to show that the application is busy.
    \sa QProgressBar
*/
class QProgressIndicator : public QWidget
{
    Q_OBJECT
    Q_PROPERTY(int delay READ animationDelay WRITE setAnimationDelay)
    Q_PROPERTY(bool displayedWhenStopped READ isDisplayedWhenStopped WRITE setDisplayedWhenStopped)
    Q_PROPERTY(QColor color READ color WRITE setColor)
public:
    QProgressIndicator(QWidget* parent = 0);

    /*! Returns the delay between animation steps.
        \return The number of milliseconds between animation steps. By default, the animation delay is set to 40 milliseconds.
        \sa setAnimationDelay
     */
    int animationDelay() const { return m_delay; }

    /*! Returns a Boolean value indicating whether the component is currently animated.
        \return Animation state.
        \sa startAnimation stopAnimation
     */
    bool isAnimated () const;

    /*! Returns a Boolean value indicating whether the receiver shows itself even when it is not animating.
        \return Return true if the progress indicator shows itself even when it is not animating. By default, it returns false.
        \sa setDisplayedWhenStopped
     */
    bool isDisplayedWhenStopped() const;

    /*! Returns the color of the component.
        \sa setColor
      */
    const QColor & color() const { return m_color; }

    virtual QSize sizeHint() const;
    int heightForWidth(int w) const;
public slots:
    /*! Starts the spin animation.
        \sa stopAnimation isAnimated
     */
    void startAnimation();

    /*! Stops the spin animation.
        \sa startAnimation isAnimated
     */
    void stopAnimation();

    /*! Sets the delay between animation steps.
        Setting the \a delay to a value larger than 40 slows the animation, while setting the \a delay to a smaller value speeds it up.
        \param delay The delay, in milliseconds.
        \sa animationDelay
     */
    void setAnimationDelay(int delay);

    /*! Sets whether the component hides itself when it is not animating.
       \param state The animation state. Set false to hide the progress indicator when it is not animating; otherwise true.
       \sa isDisplayedWhenStopped
     */
    void setDisplayedWhenStopped(bool state);

    /*! Sets the color of the components to the given color.
        \sa color
     */
    void setColor(const QColor & color);
protected:
    virtual void timerEvent(QTimerEvent * event);
    virtual void paintEvent(QPaintEvent * event);
private:
    int m_angle;
    int m_timerId;
    int m_delay;
    bool m_displayedWhenStopped;
    QColor m_color;
};

#endif // QPROGRESSINDICATOR_H

2.QProgressIndicator.cpp

#include "QProgressIndicator.h"

#include <QPainter>
#include <QDebug>

/**
 *自定义动态加载类一
 * @brief QProgressIndicator::QProgressIndicator
 * @param parent
 */
QProgressIndicator::QProgressIndicator(QWidget* parent)
    : QWidget(parent),
      m_angle(0),
      m_timerId(-1),
      m_delay(40),
      m_displayedWhenStopped(false),
      m_color(Qt::black)
{
    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    setFocusPolicy(Qt::NoFocus);
}

bool QProgressIndicator::isAnimated () const
{
    return (m_timerId != -1);
}

void QProgressIndicator::setDisplayedWhenStopped(bool state)
{
    m_displayedWhenStopped = state;

    update();
}

bool QProgressIndicator::isDisplayedWhenStopped() const
{
    return m_displayedWhenStopped;
}

void QProgressIndicator::startAnimation()
{
    qDebug()<<"开启动画";
    m_angle = 0;

    if (m_timerId == -1)
        m_timerId = startTimer(m_delay);
}

void QProgressIndicator::stopAnimation()
{
    qDebug()<<"停止动画";
    if (m_timerId != -1)
        killTimer(m_timerId);

    m_timerId = -1;

    update();
}

void QProgressIndicator::setAnimationDelay(int delay)
{
    if (m_timerId != -1)
        killTimer(m_timerId);

    m_delay = delay;

    if (m_timerId != -1)
        m_timerId = startTimer(m_delay);
}

void QProgressIndicator::setColor(const QColor & color)
{
    m_color = color;

    update();
}

QSize QProgressIndicator::sizeHint() const
{
    return QSize(40,40);
}

int QProgressIndicator::heightForWidth(int w) const
{
    return w;
}

void QProgressIndicator::timerEvent(QTimerEvent * /*event*/)
{
    m_angle = (m_angle+30)%360;

    update();
}

void QProgressIndicator::paintEvent(QPaintEvent * /*event*/)
{
    if (!m_displayedWhenStopped && !isAnimated())
        return;

    int width = qMin(this->width(), this->height());

    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);

    int outerRadius = (width-1)*0.5;
    int innerRadius = (width-1)*0.5*0.38;

    int capsuleHeight = outerRadius - innerRadius;
    int capsuleWidth  = (width > 32 ) ? capsuleHeight *.23 : capsuleHeight *.35;
    int capsuleRadius = capsuleWidth/2;

    for (int i=0; i<12; i++)
    {
        QColor color = m_color;
        color.setAlphaF(1.0f - (i/12.0f));
        p.setPen(Qt::NoPen);
        p.setBrush(color);
        p.save();
        p.translate(rect().center());
        p.rotate(m_angle - i*30.0f);
        p.drawRoundedRect(-capsuleWidth*0.5, -(innerRadius+capsuleHeight), capsuleWidth, capsuleHeight, capsuleRadius, capsuleRadius);
        p.restore();
    }
}

二、第二种自定义动态加载类

第二种自定义动画等待加载类Form

1.Form.h

#ifndef FORM_H
#define FORM_H

#include <QWidget>

#include <QTimer>
namespace Ui {
class Form;
}

class Form : public QWidget
{
    Q_OBJECT

public:
    explicit Form(QWidget *parent = nullptr);
    ~Form();
    void StartAnimation();//开始动画
    void StopAnimation();//停止动画
private:
    void colorLoop(QColor *);
protected:
    void paintEvent(QPaintEvent *event);
private:
    Ui::Form *ui;
    QColor m_color[8];
    QPoint m_point[8];
    int m_inRadius;
    int m_outRadius;
    int m_outRadiuslist[8];
    QTimer *m_timer;
    bool m_displayedWhenStopped = true;//停止显示动画的标识,默认为true
};

#endif // FORM_H

2.form.cpp

#include "form.h"
#include "ui_form.h"
#include <QPainter>
#include <QLabel>
#include <QDebug>
/**
 *自定义动态加载类二
 * @brief Form::Form
 * @param parent
 */
Form::Form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form)
{
    ui->setupUi(this);

    setWindowTitle("Loading . . .");

    m_inRadius = 30;
    m_outRadius = 5;
    //效果1
//    m_color[0] = QColor(255,140,0);
//    m_color[1] = QColor(255,140,0);
//    m_color[2] = QColor(255,140,0);
//    m_color[3] = QColor(255,140,0);
//    m_color[4] = QColor(34,139,34);
//    m_color[5] = QColor(34,139,34);
//    m_color[6] = QColor(34,139,34);
//    m_color[7] = QColor(34,139,34);

//    m_outRadiuslist[0] = 8;
//    m_outRadiuslist[1] = 8;
//    m_outRadiuslist[2] = 8;
//    m_outRadiuslist[3] = 8;
//    m_outRadiuslist[4] = 8;
//    m_outRadiuslist[5] = 8;
//    m_outRadiuslist[6] = 8;
//    m_outRadiuslist[7] = 10;

    //效果2
    m_color[0] = QColor(9,126,186);
    m_color[1] = QColor(9,126,186);
    m_color[2] = QColor(9,126,186);
    m_color[3] = QColor(9,126,186);
    m_color[4] = QColor(9,126,186);
    m_color[5] = QColor(9,126,186);
    m_color[6] = QColor(9,126,186);
    m_color[7] = QColor(9,126,186);

    m_outRadiuslist[0] = 1;
    m_outRadiuslist[1] = 2;
    m_outRadiuslist[2] = 3;
    m_outRadiuslist[3] = 4;
    m_outRadiuslist[4] = 5;
    m_outRadiuslist[5] = 6;
    m_outRadiuslist[6] = 7;
    m_outRadiuslist[7] = 8;


    m_point[0] = QPoint(this->width()/2-m_outRadius-m_inRadius,
                        this->height()/2-m_outRadius);//左
    m_point[1] = QPoint(this->width()/2-m_outRadius-m_inRadius*2/3,
                        this->height()/2-m_outRadius-m_inRadius*2/3);//左上
    m_point[2] = QPoint(this->width()/2-m_outRadius,
                        this->height()/2-m_outRadius-m_inRadius);//上
    m_point[3] = QPoint(this->width()/2-m_outRadius+m_inRadius*2/3,
                        this->height()/2-m_outRadius-m_inRadius*2/3);//右上
    m_point[4] = QPoint(this->width()/2-m_outRadius+m_inRadius,
                        this->height()/2-m_outRadius);//右
    m_point[5] = QPoint(this->width()/2-m_outRadius+m_inRadius*2/3,
                        this->height()/2-m_outRadius+m_inRadius*2/3);//右下
    m_point[6] = QPoint(this->width()/2-m_outRadius,
                        this->height()/2-m_outRadius+m_inRadius);//下
    m_point[7] = QPoint(this->width()/2-m_outRadius-m_inRadius*2/3,
                        this->height()/2-m_outRadius+m_inRadius*2/3);//左下

    m_timer = new QTimer(this);
    connect(m_timer,&QTimer::timeout,this,[=](){
        colorLoop(m_color);
        update();
    });
}

Form::~Form()
{
    delete ui;
}

void Form::StartAnimation()
{
    qDebug()<<"开始动画";
    m_displayedWhenStopped= false;
    m_timer->start(100);
}

void Form::StopAnimation()
{
    qDebug()<<"停止动画";
    m_timer->stop();
    m_displayedWhenStopped= true;
    update();
}

void Form::colorLoop(QColor *color)
{
    QColor tmp = m_color[7];
    int tmpInt = m_outRadiuslist[7];
    for (int var = 7; var > 0; --var) {
       m_color[var] = m_color[var-1];
       m_outRadiuslist[var] = m_outRadiuslist[var-1];
    }
    m_color[0] = tmp;
    m_outRadiuslist[0] = tmpInt;
}

void Form::paintEvent(QPaintEvent *event)
{
    //创建画笔
    QPainter painter(this);
    //抗锯齿和使用平滑转换算法
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);

    for (int var = 0; var < 8; ++var) {
        QPen pen(m_color[var]);//定义画笔
        pen.setWidth(1);//
        pen.setStyle(Qt::CustomDashLine);
        painter.setPen(pen);
        painter.setBrush(QBrush(m_color[var], Qt::SolidPattern));
       painter.drawEllipse(m_point[var],m_outRadiuslist[var],m_outRadiuslist[var]);
       }
}

三、动画效果展示

Widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QProgressIndicator.h>
#include <QFutureWatcher>
#include "form.h"
namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();
private slots:
    void on_start1_clicked();

    void on_start2_clicked();

private:
    Ui::Widget *ui;
    //自定义动态加载类一
    QProgressIndicator *pIndicator = nullptr;
     //自定义动态加载类二
    Form *form = nullptr;
};

#endif // WIDGET_H

Widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QHBoxLayout>
//查询数据库中的内容实现异步操作
#include <QtConcurrent/QtConcurrent>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}


//自定义动态加载类一
void Widget::on_start1_clicked()
{
    //动画居中显示
    pIndicator = new QProgressIndicator(this);
    QHBoxLayout *hLayout = new QHBoxLayout();// 水平布局
    hLayout->setMargin(0);      // 与窗体边无距离 尽量占满
    hLayout->addWidget(pIndicator);     // 加入控件
    hLayout->setAlignment(pIndicator, Qt::AlignCenter); // 控件居中
    ui->tableView->setLayout(hLayout);
    pIndicator->setColor(QColor(9,126,186));

    //监视异步操作的结果
    QFutureWatcher<void> *pwatcher = new QFutureWatcher<void>;
    pIndicator->startAnimation();//启动动画
    //异步操作
    QFuture<void> future = QtConcurrent::run([=]()
    {
       QThread::msleep(5000); //模拟耗时操作
    });

    connect(pwatcher, &QFutureWatcher<void>::finished, this, [=]()
    {
        //主线程操作
        pIndicator->stopAnimation();//关闭动画
    });
    pwatcher->setFuture(future);

}
//自定义动态加载类二
void Widget::on_start2_clicked()
{
    form = new Form(ui->tableView_2);
    form->show();
    //监视异步操作的结果
    QFutureWatcher<void> *pwatcher = new QFutureWatcher<void>;
    form->StartAnimation();//启动动画
    //异步操作
    QFuture<void> future = QtConcurrent::run([=]()
    {
       QThread::msleep(5000); //模拟耗时操作
    });

    connect(pwatcher, &QFutureWatcher<void>::finished, this, [=]()
    {
        //主线程操作
        form->StopAnimation();//关闭动画
        form->hide();
    });
    pwatcher->setFuture(future);
}

效果如图:
在这里插入图片描述
在这里插入图片描述
都模拟耗时5s后停止动画。

四、总结

采用QtConcurrent::run实现异步耗时操作时一定要通过QFutureWatcher异步监测耗时操作结果完成后再进行主线程操作,否则会出现异步跨线程调用的错误。
但在QtConcurrent::run中采用QSqltablemodel模型对数据库进行耗时操作时会出现阻塞主线程的问题,目前该问题未解决,请各位大神在评论区留言帮我答疑。

  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yellow Small Tiger

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值