Qt界面之侧边栏隐藏和滑出

一、前言

  在实际的Qt界面布局设计中,特别是主界面中,经常会用到侧边栏的方式,然后在其中加入其他控件来复合使用,下面简单来实现一下Qt侧边栏的隐藏和显示,效果如下:
Qt界面之侧边栏隐藏和滑出_第1张图片

二、功能介绍

  界面控件很简单,主界面QWidget,侧边栏也用一个QWidget和一个按钮QPushbutton来进行组合。通过点击按钮来显示和隐藏侧边栏。主要用到的是控件的move()函数,配合QPropertyAnimation实现动画效果滑动显示隐藏。
Qt界面之侧边栏隐藏和滑出_第2张图片

三、源码

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


#pragma execution_character_set("utf-8")

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    ,m_bSideflag(false)
{
    ui->setupUi(this);

    //    this->setWindowFlags(Qt::FramelessWindowHint);
    //    ui->sidewidget->move(this->rect().width() - ui->sidewidget->width(),0); // 右侧停靠

    ui->sidewidget->move(-ui->sidewidget->width(),0);// 左侧停靠
    ui->pushButton->move(-1,ui->sidewidget->height()/2);
    ui->pushButton->setIcon(QIcon(":images/right.png"));
    m_propertyAnimation = new QPropertyAnimation(ui->sidewidget,"geometry");
    m_propertyAnimation->setEasingCurve(QEasingCurve::InOutQuint);
    m_propertyAnimation->setDuration(300);

    m_propertyAnimation2 = new QPropertyAnimation(ui->pushButton,"geometry");
    m_propertyAnimation2->setEasingCurve(QEasingCurve::InOutQuint);
    m_propertyAnimation2->setDuration(200);
}

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

void Widget::on_pushButton_clicked()
{
    //显示侧边栏
    if(!m_bSideflag)
    {
        m_propertyAnimation->setStartValue(QRect(-this->rect().width(),0,ui->sidewidget->width(),ui->sidewidget->height()));
        m_propertyAnimation->setEndValue(QRect(0,0,ui->sidewidget->width(),ui->sidewidget->height()));
        m_propertyAnimation->start();

        m_propertyAnimation2->setStartValue(QRect(-1,ui->sidewidget->height()/2,ui->pushButton->width(),ui->pushButton->height()));
        m_propertyAnimation2->setEndValue(QRect(ui->sidewidget->width()-2,ui->sidewidget->height()/2,ui->pushButton->width(),ui->pushButton->height()));
        m_propertyAnimation2->start();

        ui->pushButton->setIcon(QIcon(":images/left.png"));

        m_bSideflag = !m_bSideflag;
    }
    else
    {
        m_propertyAnimation->setStartValue(QRect(0,0,ui->sidewidget->width(),ui->sidewidget->height()));
        m_propertyAnimation->setEndValue(QRect(-this->rect().width(),0,ui->sidewidget->width(),ui->sidewidget->height()));
        m_propertyAnimation->start();

        m_propertyAnimation2->setStartValue(QRect(ui->sidewidget->width()-2,ui->sidewidget->height()/2,ui->pushButton->width(),ui->pushButton->height()));
        m_propertyAnimation2->setEndValue(QRect(-1,ui->sidewidget->height()/2,ui->pushButton->width(),ui->pushButton->height()));
        m_propertyAnimation2->start();

        ui->pushButton->setIcon(QIcon(":images/right.png"));

        m_bSideflag = !m_bSideflag;
    }
}

你可能感兴趣的:(QT,qt,ui,Qt侧边栏)