Qt全屏顯示和按鍵ESC退出全屏

一字千金發表於2024-10-12

1.需求描述

將播放視窗全屏顯示,將工具欄邊框等隱藏在後面;然後退出全屏透過ESC返回按鈕;

2.實現方法

定義一個全屏的容器類,繼承於QWidget;全屏時,去掉視窗的父視窗,然後全屏顯示,不去掉父視窗指標無法全屏;按下ESC按鈕後,透過keyPressEvent(QKeyEvent* pEvent);函式,將父視窗重新設定回去;

#ifndef FULLSCREEN_H
#define FULLSCREEN_H

#include <QWidget>
#include <QKeyEvent>
class FullScreen : public QWidget
{
    Q_OBJECT

public:
    FullScreen(QWidget *parent);
    ~FullScreen();
    void SetFullScreen();
    void keyPressEvent(QKeyEvent* pEvent);
private:
    QWidget* parentwidget=NULL;
};

#endif // FULLSCREEN_H
#include "FullScreen.h"
#include <QLayout>
FullScreen::FullScreen(QWidget *parent)
    : QWidget(parent)
{

}

FullScreen::~FullScreen()
{

}

void FullScreen::SetFullScreen()
{
    parentwidget = parentWidget();
    parentWidget()->layout()->removeWidget(this);
    setParent(NULL);
    showFullScreen();
    raise();
}

void FullScreen::keyPressEvent(QKeyEvent* pEvent)
{
    if (!pEvent->modifiers())
    {
        if (pEvent->key() == Qt::Key_Escape &&isFullScreen())
        {
            hide();//避免一閃而過
            showNormal();
            setParent(parentwidget);
            parentwidget->layout()->addWidget(this);
            show();
            pEvent->accept();
            return;
        }
    }
    QWidget::keyPressEvent(pEvent);
}

相關文章