웹엔진 위젯 비디오 플레이어 예제

QWebEngineView 를 사용하여 전체 화면 비디오를 표시합니다.

비디오 플레이어는 QWebEngineView 를 사용하여 HTML5 비디오의 전체 화면 재생을 지원하는 방법을 보여줍니다.

전체 화면 API는 웹 페이지에서 HTML 요소 중 하나가 사용자의 전체 화면을 차지하도록 요청할 수 있는 크로스 브라우저 자바스크립트 API입니다. 일반적으로 <video> 요소를 통한 전체 화면 동영상 재생에 사용되지만 원칙적으로 모든 HTML 콘텐츠를 전체 화면 모드로 표시하는 데 사용할 수 있습니다. Qt WebEngine 은 이 API를 지원하지만 기본적으로 비활성화되어 있습니다. 이 예에서는 이를 켜는 데 필요한 단계를 보여줍니다:

예제 실행하기

에서 예제를 실행하려면 Qt Creator에서 Welcome 모드를 열고 Examples 에서 예제를 선택합니다. 자세한 내용은 예제 만들기 및 실행하기를 참조하세요.

개요

예제 프로그램이 시작되면 임베드된 YouTube 동영상 플레이어가 표시된 QWebEngineView 이 있는 일반(전체 화면이 아닌) 창이 생성됩니다. 그런 다음 전체 화면 토글 버튼(오른쪽 하단 모서리)을 클릭하여 전체 화면 모드로 전환할 수 있습니다. 그러면 이스케이프 키를 눌러 전체 화면 모드를 종료할 수 있음을 알리는 알림 오버레이가 중앙에 표시됩니다.

구현상 전체 화면 모드로 들어가려면 별도의 QWebEngineView 인스턴스가 있는 새 전체 화면 창을 만들고 일반 창의 QWebEngineView 에서 이 새 QWebEngineView 으로 QWebEnginePage 을 마이그레이션해야 합니다. 전체 화면 모드를 종료하면 이 마이그레이션이 취소됩니다.

예제 코드는 MainWindow, FullScreenWindow, FullScreenNotification 의 세 가지 클래스로 나뉩니다. MainWindowFullScreenWindow 클래스는 각각 하나의 최상위 창을 관리하고 FullScreenNotification 클래스는 알림 상자의 스타일링 및 애니메이션을 담당합니다. MainWindow 은 시작 시 생성되어 전체 프로그램 런타임 동안 유지되는 반면, FullScreenWindow 은 전체 화면 모드로 들어갈 때마다 새로 생성됩니다.

메인윈도우 클래스 선언

MainWindowQWebEngineView 을 중앙 위젯으로 하는 QMainWindow 입니다:

#include "fullscreenwindow.h"

#include <QMainWindow>
#include <QWebEngineView>
#include <QWebEngineFullScreenRequest>

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void fullScreenRequested(QWebEngineFullScreenRequest request);

private:
    QWebEngineView *m_view;
    QScopedPointer<FullScreenWindow> m_fullScreenWindow;
};

MainWindow 클래스 정의

생성자에서는 QWebEngineView 을 중앙 위젯으로 설정하는 것으로 시작합니다:

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_view(new QWebEngineView(this))
{
    setCentralWidget(m_view);

그런 다음 Qt WebEngine 을 구성하여 전체 화면 API에 대한 지원을 알립니다:

    m_view->settings()->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);

이 줄이 없으면 페이지에서 실행 중인 자바스크립트가 브라우저가 전체 화면 모드를 지원하지 않는다는 것을 감지할 수 있으므로 전체 화면 토글 버튼이 비활성화(회색으로 표시됨)됩니다.

다음으로 fullScreenRequested 신호를 슬롯에 연결합니다:

    connect(m_view->page(),
            &QWebEnginePage::fullScreenRequested,
            this,
            &MainWindow::fullScreenRequested);

이 신호는 페이지의 자바스크립트가 전체 화면 모드로 전환하거나 종료하려고 할 때마다 전송됩니다. 이 신호를 처리하지 않으면( FullScreenSupportEnabled 속성은 true 으로 유지) 토글 버튼이 활성화되지만 자바스크립트의 전체 화면 요청이 거부되므로 토글 버튼을 클릭해도 아무런 효과가 없습니다.

마지막으로 예제에 포함된 HTML( webenginewidgets/videoplayer/data/index.html 참조)을 QWebEngineView 에 로드합니다:

    m_view->load(QUrl(QStringLiteral("qrc:/index.html")));

MainWindow 의 두 번째 부분은 전체 화면 요청을 처리합니다:

void MainWindow::fullScreenRequested(QWebEngineFullScreenRequest request)
{
    if (request.toggleOn()) {
        if (m_fullScreenWindow)
            return;
        request.accept();
        m_fullScreenWindow.reset(new FullScreenWindow(m_view));
    } else {
        if (!m_fullScreenWindow)
            return;
        request.accept();
        m_fullScreenWindow.reset();
    }
}

전체 화면 모드로 들어갈 때 FullScreenWindow 을 새로 생성하고 종료할 때 삭제합니다.

FullScreenWindow 클래스 선언

FullScreenWindowQWebEngineViewFullScreenNotification 을 포함하는 QWidget 입니다.

#include <QWidget>

QT_BEGIN_NAMESPACE
class QWebEngineView;
QT_END_NAMESPACE

class FullScreenNotification;

class FullScreenWindow : public QWidget
{
    Q_OBJECT
public:
    explicit FullScreenWindow(QWebEngineView *oldView, QWidget *parent = nullptr);
    ~FullScreenWindow();

protected:
    void resizeEvent(QResizeEvent *event) override;

private:
    QWebEngineView *m_view;
    FullScreenNotification *m_notification;
    QWebEngineView *m_oldView;
    QRect m_oldGeometry;
};

FullScreenWindow 클래스 정의

생성자는 일반 창을 숨기고(지오메트리를 저장하면서) 대신 새로운 FullScreenWindow 을 표시하는 역할을 합니다:

FullScreenWindow::FullScreenWindow(QWebEngineView *oldView, QWidget *parent)
    : QWidget(parent)
    , m_view(new QWebEngineView(this))
    , m_notification(new FullScreenNotification(this))
    , m_oldView(oldView)
    , m_oldGeometry(oldView->window()->geometry())
{
    m_view->stackUnder(m_notification);

    auto exitAction = new QAction(this);
    exitAction->setShortcut(Qt::Key_Escape);
    connect(exitAction, &QAction::triggered, [this]() {
        m_view->triggerPageAction(QWebEnginePage::ExitFullScreen);
    });
    addAction(exitAction);

    m_view->setPage(m_oldView->page());
    setGeometry(m_oldGeometry);
    showFullScreen();
    m_oldView->window()->hide();
}

QWebEngineView::setPage 을 호출하면 웹 페이지가 MainWindow 의 보기에서 FullScreenWindow 의 보기로 이동합니다.

소멸자에서는 동일한 방법을 사용하여 페이지를 다시 이동한 후 기본 창의 지오메트리와 가시성을 복원합니다:

FullScreenWindow::~FullScreenWindow()
{
    m_oldView->setPage(m_view->page());
    m_oldView->window()->setGeometry(m_oldGeometry);
    m_oldView->window()->show();
    hide();
}

QWidget::resizeEvent 을 재정의하여 QWebEngineView 을 최대로 유지하고 FullScreenNotification 을 창 중앙에 배치하여 수동 레이아웃을 수행합니다:

void FullScreenWindow::resizeEvent(QResizeEvent *event)
{
    QRect viewGeometry(QPoint(0, 0), size());
    m_view->setGeometry(viewGeometry);

    QRect notificationGeometry(QPoint(0, 0), m_notification->sizeHint());
    notificationGeometry.moveCenter(viewGeometry.center());
    m_notification->setGeometry(notificationGeometry);

    QWidget::resizeEvent(event);
}

FullScreenNotification 클래스 선언

FullScreenNotification 은 스타일과 애니메이션이 적용된 QLabel 에 불과합니다:

#include <QLabel>

class FullScreenNotification : public QLabel
{
    Q_OBJECT
public:
    FullScreenNotification(QWidget *parent = nullptr);

protected:
    void showEvent(QShowEvent *event) override;

signals:
    void shown();

private:
    bool m_previouslyVisible;
};

풀스크린윈도우 클래스 정의

생성자에서 QLabel 을 구성하고 애니메이션 프레임워크를 사용하여 지연 페이드아웃 애니메이션을 설정합니다:

FullScreenNotification::FullScreenNotification(QWidget *parent)
    : QLabel(parent)
    , m_previouslyVisible(false)
{
    setText(tr("You are now in full screen mode. Press ESC to quit!"));
    setStyleSheet(
        "font-size: 24px;"
        "color: white;"
        "background-color: black;"
        "border-color: white;"
        "border-width: 2px;"
        "border-style: solid;"
        "padding: 100px");
    setAttribute(Qt::WA_TransparentForMouseEvents);

    auto effect = new QGraphicsOpacityEffect;
    effect->setOpacity(1);
    setGraphicsEffect(effect);

    auto animations = new QSequentialAnimationGroup(this);
    animations->addPause(3000);
    auto opacityAnimation = new QPropertyAnimation(effect, "opacity", animations);
    opacityAnimation->setDuration(2000);
    opacityAnimation->setStartValue(1.0);
    opacityAnimation->setEndValue(0.0);
    opacityAnimation->setEasingCurve(QEasingCurve::OutQuad);
    animations->addAnimation(opacityAnimation);

    connect(this, &FullScreenNotification::shown,
            [animations](){ animations->start(); });

    connect(animations, &QAbstractAnimation::finished,
            [this](){ this->hide(); });
}

애니메이션을 트리거하는 데 사용하는 사용자 정의 신호 shownshowEvent 메서드에서 방출됩니다:

void FullScreenNotification::showEvent(QShowEvent *event)
{
    QLabel::showEvent(event);
    if (!m_previouslyVisible && isVisible())
        emit shown();
    m_previouslyVisible = isVisible();
}

예제 프로젝트 @ code.qt.io

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.