Qt实现菜单项动画

效果:点击  "菜单:常规"   将通过QEasingCurve::OutQuart的形式显示菜单项,如图

Qt实现菜单项动画_第1张图片

具体代码:

 

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 

class QMenu;

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

    Q_PROPERTY(QSize fixedsize READ fixedsize WRITE setfixedsize)

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

    void showAnimation();

private:
    QSize fixedsize() const;
    void setfixedsize(const QSize sz);

private:
    Ui::MainWindow *ui;

    QMenu* pMenu = nullptr;
    QSize fixedsizeValue;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include 
#include 
#include 

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    pMenu = new QMenu("菜单:常规");
    pMenu->addAction("1111");
    pMenu->addAction("2222");
    pMenu->addAction("3333");
    pMenu->addAction("4444");
    pMenu->addAction("5555");
    pMenu->addAction("6666");
    pMenu->addAction("7777");
    pMenu->addAction("8888");
    pMenu->addAction("9999");
    QMenuBar* pMenuBar  = new QMenuBar(this);
    pMenuBar->setGeometry(10,10,68,25);
    pMenuBar->addMenu(pMenu);

    pMenu->setFixedSize(0,0);
    connect(pMenu, &QMenu::aboutToShow, this, &MainWindow::showAnimation);
}

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

void MainWindow::showAnimation()
{
    //展示动画
    QPropertyAnimation* animation = new QPropertyAnimation(this, "fixedsize");
    animation->setStartValue(QSize(90, 0));
    animation->setEndValue(QSize(90, 200));
    animation->setDuration(300);
    animation->setEasingCurve(QEasingCurve::OutQuart);
    animation->start();

    connect(animation, &QPropertyAnimation::valueChanged, this, &MainWindow::fixedsize);
}

QSize MainWindow::fixedsize() const
{
    return fixedsizeValue;
}
void MainWindow::setfixedsize(const QSize sz)
{
    pMenu->setFixedSize(sz);
    fixedsizeValue = sz;
}

你可能感兴趣的:(QT,qt,ui,开发语言)