QT失去focus后自動隱藏界面


 自己開發了一個股票智能分析軟件,功能很強大,需要的點擊下面的鏈接獲取:

https://www.cnblogs.com/bclshuai/p/11380657.html

1.應用場景

在一些臨時顯示的界面,比如聲音的調節面板,設置好聲音后,不需要手動按鈕來控制隱藏,而是離開界面,或者失去focus之后自動隱藏窗口。如下圖所示。

2.實現方法

重寫下面兩個虛函數,實現離開界面和失去foucs時自動隱藏的功能

void leaveEvent(QEvent *e);                      //離開QWidget瞬間事件
    void focusOutEvent(QFocusEvent *event);//失去focus時自動隱藏

頭文件

#ifndef VOICECTRL_H
#define VOICECTRL_H

#include <QDialog>
#include "ui_voicewin.h"
class VoiceCtrl : public QDialog
{
    Q_OBJECT

public:
    VoiceCtrl();
    ~VoiceCtrl();
    Ui::VoiceCtrl ui;
protected:
    void enterEvent(QEvent *e);                      //進入QWidget瞬間事件
    void leaveEvent(QEvent *e);                      //離開QWidget瞬間事件
    void focusOutEvent(QFocusEvent *event);//失去focus時自動隱藏
private:
};

#endif // VOICECTRL_H

 

源文件

#include "VoiceCtrl.h"

VoiceCtrl::VoiceCtrl()
{
    ui.setupUi(this);
    setWindowModality(Qt::NonModal);
    setWindowFlags(Qt::FramelessWindowHint| Qt::WindowStaysOnTopHint);
    //setAttribute(Qt::WA_TranslucentBackground, true);//背景設置透明
    this->resize(36, 112);
    connect(ui.checkBoxVolume, &QCheckBox::clicked, this, [=]() {
    if (ui.checkBoxVolume->isChecked())
    {
        ui.horizontalSliderSimilarity->setValue(0);
    } 
    else
    {
        ui.horizontalSliderSimilarity->setValue(50);
    }
    });
    connect(ui.horizontalSliderSimilarity, &QSlider::valueChanged, this, [=]() {
        if (ui.horizontalSliderSimilarity->value()==0)
        {
            ui.checkBoxVolume->setChecked(true);
        }
        else
        {
            ui.checkBoxVolume->setChecked(false);
        }
    });
    
}

VoiceCtrl::~VoiceCtrl()
{
    
}
void VoiceCtrl::enterEvent(QEvent *e)
{
    show();
}

void VoiceCtrl::leaveEvent(QEvent *e)//離開隱藏closebutton
{
    hide();
}

void VoiceCtrl::focusOutEvent(QFocusEvent * event)
{
    //如果是點擊界面上的控件,聲音控制界面也會失去focus,所以點擊界面上的控件時,這里返回不隱藏
    if (ui.checkBoxVolume->hasFocus()||ui.horizontalSliderSimilarity->hasFocus())
    {
        return;
    }
    hide();
}

3.創建對象並使用

在需要使用聲音調節面板的地方,創建VoiceCtrl對象,通過點擊按鈕,來顯示聲音控制面板到按鈕的上方,離開控制面板或失去focus之后自動隱藏。

//顯示聲音調節界面
    {
        QPoint point = this->mapToGlobal(ui.PlayWndToolbar_RightWnd->pos());
        m_volumeCtrl.move(point.x()-4, point.y() - 110);
        m_volumeCtrl.show(); 

//最關鍵的一步,一定要將界面對象設置為該屬性,否則無法實現點擊其他地方,聲音界面無focus時自動隱藏。
        m_volumeCtrl.setFocus(Qt::ActiveWindowFocusReason); 
    }

ActiveWindowFocusReason說明

public static final Qt.FocusReason ActiveWindowFocusReason

The window system made this window either active or inactive.

 



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM