qt中,在一个qwidget完成几何变形动画后,我想恢复它之前的高宽
时间: 2025-07-06 11:58:03 浏览: 5
### 实现 QWidget 的几何变形动画并恢复原始大小
为了实现在 Qt 中对 `QWidget` 进行几何变形动画并在动画结束后恢复到原来的尺寸,可以采用以下方法:
#### 使用 QPropertyAnimation 类
通过 `QPropertyAnimation` 可以为任何具有属性的对象创建平滑过渡效果。对于 `QWidget` 来说,通常会操作其 geometry 属性来进行位置和大小的变化。
```cpp
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QPropertyAnimation>
class AnimatedWidget : public QWidget {
public:
explicit AnimatedWidget(QWidget *parent = nullptr);
protected slots:
void startAnimation();
private:
QPushButton *button;
};
AnimatedWidget::AnimatedWidget(QWidget *parent)
: QWidget(parent), button(new QPushButton("Start Animation", this)) {
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(button);
connect(button, &QPushButton::clicked, this, &AnimatedWidget::startAnimation);
}
void AnimatedWidget::startAnimation() {
// 记录初始状态
QRect originalGeometry = this->geometry();
// 创建新的目标矩形 (缩小后的尺寸作为例子)
QRect targetGeometry = this->geometry().adjusted(0, 0, -100, -50);
// 动画对象实例化
QPropertyAnimation *animation = new QPropertyAnimation(this, "geometry");
animation->setDuration(1000); // 设置持续时间为一秒
animation->setStartValue(originalGeometry); // 开始值为原尺寸
animation->setEndValue(targetGeometry); // 结束值为目标尺寸
QObject::connect(animation,SIGNAL(finished()),this,SLOT(startRestoreAnimation()));
// 启动动画
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
// 定义一个槽函数用于启动恢复动画
void AnimatedWidget::startRestoreAnimation(){
// 获取最初的矩形区域
static const QRect& originalGeometry = this->property("originalGeometry").toRect();
// 新建另一个动画负责还原过程
auto* restoreAnim = new QPropertyAnimation(this,"geometry");
restoreAnim->setDuration(800);
restoreAnim->setStartValue(this->geometry());
restoreAnim->setEndValue(originalGeometry);
// 执行恢复动作
restoreAnim->start(QAbstractAnimation::DeleteWhenStopped);
}
```
上述代码展示了如何定义一个自定义的小部件类 `AnimatedWidget` 并为其添加按钮触发器以开始缩放动画,在第一次变换完成后自动调用第二个动画来返回原来的状态[^1]。
需要注意的是,当首次执行改变形状的操作前应当保存好原件件的位置与大小信息以便后续能够正确无误地将其复位;另外还可以考虑利用信号机制连接第一个动画完成事件至第二阶段的初始化工作之上从而简化逻辑控制流程[^2]。
阅读全文
相关推荐


















