You need to enable JavaScript to run this app. 使用QPropertyAnimation实现表单分组框展开收起动画效果异常如何优化
优惠活动
大模型
产品
解决方案
定价
更多

使用QPropertyAnimation实现表单分组框展开收起动画效果异常如何优化

问题根源

  • 初始化逻辑错误:UI加载后窗口高度为包含groupBox的展开状态高度,仅隐藏groupBox但未同步缩小窗口,导致首次展开时动画起止高度一致无过渡效果
  • 未设置动画起始值:每次新建的动画未明确指定起始大小,仅设置结束值容易出现跳变
  • 内存泄漏:每次点击都新建QPropertyAnimation对象,无回收逻辑
  • 控件可见时机不合理:展开时直接显示groupBox,未与窗口拉伸动画同步

优化后实现

头文件 widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QPropertyAnimation>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private slots:
    void on_pushButton_clicked();

private:
    Ui::Widget *ui;
    QPropertyAnimation *m_animation;
    bool m_isExpand = false;
    int m_expandHeight; // 展开状态总高度
    int m_shrinkHeight; // 收起状态总高度
};
#endif // WIDGET_H

实现文件 widget.cpp

#include "widget.h"
#include "./ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent), ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 预计算两种状态的高度
    m_expandHeight = this->height();
    m_shrinkHeight = m_expandHeight - ui->groupBox->height();
    // 初始化窗口为收起状态
    this->resize(this->width(), m_shrinkHeight);
    ui->groupBox->setVisible(false);
    ui->pushButton->setText("展开");

    // 初始化动画对象,复用无需重复创建
    m_animation = new QPropertyAnimation(this, "size", this);
    m_animation->setDuration(250);
    m_animation->setEasingCurve(QEasingCurve::InOutQuad); // 更平滑的缓动效果
}

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

void Widget::on_pushButton_clicked()
{
    m_animation->stop(); // 停止正在进行的动画避免冲突
    if(!m_isExpand){
        // 展开逻辑
        ui->groupBox->setVisible(true);
        m_animation->setStartValue(QSize(this->width(), m_shrinkHeight));
        m_animation->setEndValue(QSize(this->width(), m_expandHeight));
        ui->pushButton->setText("收起");
        m_isExpand = true;
    }else{
        // 收起逻辑,动画结束后再隐藏groupBox避免提前消失
        ui->pushButton->setText("展开");
        m_animation->setStartValue(QSize(this->width(), m_expandHeight));
        m_animation->setEndValue(QSize(this->width(), m_shrinkHeight));
        // 绑定动画结束信号,收起完成再隐藏groupBox
        disconnect(m_animation, &QPropertyAnimation::finished, nullptr, nullptr);
        connect(m_animation, &QPropertyAnimation::finished, this, [=](){
            ui->groupBox->setVisible(false);
        });
        m_isExpand = false;
    }
    m_animation->start();
}

额外注意事项

  • 请确保窗口内控件使用垂直布局(QVBoxLayout)排列,避免动画过程中控件错位、裁剪异常
  • 可根据需求调整动画时长和缓动曲线类型,达到更符合预期的过渡效果

内容的提问来源于stack exchange,提问作者Lincoln Ingaroca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 01:15:03