当前位置:首页 > 编程笔记 > 正文
已解决

Qt:关闭对话框,动画实现窗体逐渐缩小到消失

来自网友在路上 11018101提问 提问时间:2023-11-01 18:20:54阅读次数: 101

最佳答案 问答题库1018位专家为你答疑解惑

关键技术:

1、使用QPropertyAnimation对象,实现动画效果,逐渐缩小窗体尺寸,以及透明度;

2、在对话框缩小时,要将界面中的控件都隐藏起来,并且将对话框布局的Margin修改成0

代码如下:

dialog.h

#ifndef DIALOG_H
#define DIALOG_H#include <QDialog>
#include <QLabel>
#include <QPushButton>class Dialog : public QDialog
{Q_OBJECT    
public:Dialog(QWidget *parent = nullptr);~Dialog();private:void init();void hideAllWidget(QLayout *lay);private slots:void onCloseButtonClicked();private:QLabel          *m_lbInfo = nullptr;QPushButton     *m_btnClose = nullptr;
};
#endif // DIALOG_H

dialog.cpp

#include "dialog.h"
#include <QVBoxLayout>
#include <QPropertyAnimation>
#include <QParallelAnimationGroup>Dialog::Dialog(QWidget *parent): QDialog(parent)
{init();
}Dialog::~Dialog()
{
}void Dialog::init()
{this->setMaximumSize(500, 400);//  去掉标题栏this->setWindowFlags(Qt::FramelessWindowHint);m_lbInfo = new QLabel(this);m_btnClose = new QPushButton("关闭", this);m_lbInfo->setWordWrap(true);m_lbInfo->setText("秦时明月汉时关,\n万里长征人未还。\n但使龙城飞将在,\n不教胡马度阴山。");m_btnClose->setFixedSize(100, 32);QVBoxLayout *vLay = new QVBoxLayout(this);vLay->setMargin(50);vLay->setSpacing(60);vLay->addWidget(m_lbInfo, 0, Qt::AlignCenter);vLay->addWidget(m_btnClose, 0, Qt::AlignRight);connect(m_btnClose, &QPushButton::clicked, this, &Dialog::onCloseButtonClicked);
}void Dialog::hideAllWidget(QLayout *lay)
{if (!lay)return;lay->setMargin(0);for (int i = 0; i < lay->count(); ++i) {QLayout *subLay = lay->itemAt(i)->layout();if (subLay) {hideAllWidget(subLay);}QWidget *wgt = lay->itemAt(i)->widget();if (wgt) {wgt->hide();}}
}void Dialog::onCloseButtonClicked()
{// 隐藏所有的组件,因为这些组件若显示的话,就会占据一定的位置,对话框就不能缩小到0hideAllWidget(this->layout());const QRect &currRect = this->geometry();// 实现对话框逐渐缩小的动画QPropertyAnimation *pAnim1 = new QPropertyAnimation(this, "geometry");pAnim1->setStartValue(currRect);pAnim1->setEndValue(QRect(currRect.x(), currRect.y(), 0, 0));pAnim1->setEasingCurve(QEasingCurve::Linear);pAnim1->setDuration(600);// 实现对话框逐渐隐退的动画QPropertyAnimation *pAnim2 = new QPropertyAnimation(this, "windowOpacity");pAnim2->setStartValue(1);pAnim2->setEndValue(0.5);pAnim2->setDuration(600);QParallelAnimationGroup *animGrp = new QParallelAnimationGroup(this);animGrp->addAnimation(pAnim1);animGrp->addAnimation(pAnim2);animGrp->start(QAbstractAnimation::DeleteWhenStopped);connect(animGrp, &QParallelAnimationGroup::finished, this, &Dialog::close);
}

效果图如下:

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"Qt:关闭对话框,动画实现窗体逐渐缩小到消失":http://eshow365.cn/6-29527-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!