关键技术:
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()
{
// 隐藏所有的组件,因为这些组件若显示的话,就会占据一定的位置,对话框就不能缩小到0
hideAllWidget(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);
}
效果图如下: