【Qt】自定义标题栏并实现最小化/最大化/关闭窗口功能

之前实现了自定义窗口的拖拽移动,见【Qt】自定义标题栏并实现鼠标拖拽移动 今天实现系统按钮:最小化、最大化、关闭窗口

1.先去掉窗口的边框

/* 标题栏样式 */  
this->setWindowFlags(Qt::FramelessWindowHint |  
                     Qt::WindowSystemMenuHint |  
                     Qt::WindowMinMaxButtonsHint);  

2.添加三个私有槽,与一个记录窗口当前状态的变量,并设置初值为 true

private slots:
    /* custom system btn */
    void onMin( bool );
    void onMaxOrNormal( bool );
    void onClose( bool );
private:
    bool maxOrNormal;//true表示当前窗口状态为normal,图标应显示为max

3.添加三个自定义的按钮,图标根据Ui需求确定,我使用系统图标,并连接信号槽

    /* custom system btn */
    ui->btn_close->setStyleSheet("border:none;");
    ui->btn_min->setStyleSheet("border:none;");
    ui->btn_max_nor->setStyleSheet("border:none;");//去掉边框
    QIcon icon;
    icon = style()->standardIcon( QStyle::SP_TitleBarMinButton );
    ui->btn_min->setIcon( icon );
    if( maxOrNormal ){// true represents Max
        icon = style()->standardIcon( QStyle::SP_TitleBarMaxButton );
        ui->btn_max_nor->setIcon( icon );
    }else{
        icon = style()->standardIcon( QStyle::SP_TitleBarNormalButton );
        ui->btn_max_nor->setIcon( icon );
    }
    icon = style()->standardIcon( QStyle::SP_TitleBarCloseButton );
    ui->btn_close->setIcon( icon );

    connect( ui->btn_min, SIGNAL(clicked(bool)), this, SLOT( onMin(bool)) );
    connect( ui->btn_max_nor, SIGNAL(clicked(bool)), this, SLOT( onMaxOrNormal(bool)) );
    connect( ui->btn_close, SIGNAL(clicked(bool)), this, SLOT( onClose(bool)) );

4.槽函数源代码:

void MainWindow::onMin(bool)
{
    if( windowState() != Qt::WindowMinimized ){
        setWindowState( Qt::WindowMinimized );
    }
}

void MainWindow::onMaxOrNormal(bool)
{
    QIcon icon;
    if( maxOrNormal ){
        icon = style()->standardIcon( QStyle::SP_TitleBarNormalButton );
        ui->btn_max_nor->setIcon( icon );
        setWindowState( Qt::WindowMaximized );
    }else {
        icon = style()->standardIcon( QStyle::SP_TitleBarMaxButton );
        ui->btn_max_nor->setIcon( icon );
        setWindowState( Qt::WindowNoState );
    }
    maxOrNormal = !maxOrNormal;
}

void MainWindow::onClose(bool)
{
    close();
}
5.注意事项

1)设置窗口最大化、最小化、原状态也可以使用如下方法

    showMaximized();
    showMinimized();
    showNormal();
2)窗口normal状态是Qt:WindowNoState, 关于Qt::WindowStates有如下几种:

Constant	Value	Description
Qt::WindowNoState	0x00000000	The window has no state set (in normal state).
Qt::WindowMinimized	0x00000001	The window is minimized (i.e. iconified).
Qt::WindowMaximized	0x00000002	The window is maximized with a frame around it.
Qt::WindowFullScreen	0x00000004	The window fills the entire screen without any frame around it.
Qt::WindowActive	0x00000008	The window is the active window, i.e. it has keyboard focus.








你可能感兴趣的:(QT)