웹엔진 알림 예제
HTML5 웹 알림을 사용자에게 전달하는 방법을 보여줍니다.
WebEngine Notifications는 QWebEngineProfile::setNotificationPresenter() 메서드와 QWebEngineNotification 클래스를 사용하여 HTML5 웹 알림을 사용자에게 표시하는 방법을 보여줍니다.
예제 실행하기
에서 예제를 실행하려면 Qt Creator에서 Welcome 모드를 열고 Examples 에서 예제를 선택합니다. 자세한 내용은 예제 빌드 및 실행하기를 참조하세요.
HTML 페이지
이 예에서는 리소스 컬렉션 파일(.qrc)을 통해 추가되는 내부 HTML 페이지를 만듭니다. 이 페이지에는 권한 요청을 위한 버튼이 표시되며 이 요청을 트리거하는 데 필요한 JavaScript 코드가 포함되어 있습니다:
Notification.requestPermission().then(function (permission) { if (permission == 'granted') createNotification() })
또한 페이지에는 알림을 만들기 위한 버튼이 포함되어 있습니다. 누르면 다음과 같은 자바스크립트 구조가 실행됩니다:
function createNotification() { let title = 'Notification #' + ++notificationsCreated let options = { body: 'Visit doc.qt.io for more info!', icon: 'icon.png', } let notification = new Notification(title, options) }
주요 함수
main
함수에서는 QWebEngineView 을 인스턴스화하여 내부 HTML 페이지를 로드하고 알림 처리에 필요한 콜백을 설정합니다.
기능 권한 요청하기
그런 다음 QWebEnginePage::permissionRequested() 호출을 사용하여 사용자의 디바이스에 알림을 표시할 수 있는 권한을 요청합니다.
QObject::connect(view.page(), &QWebEnginePage::permissionRequested, [&] (QWebEnginePermission permission) { if (permission.permissionType() != QWebEnginePermission::PermissionType::Notifications) return; permission.grant(); });
새 알림 처리하기
그런 다음 HTML 웹 알림의 데이터를 캡슐화하는 NotificationPopup
을 작성합니다. 또한 QWebEngineProfile::setNotificationPresenter() 호출을 사용하여 모든 새 알림을 처리하기 위해 popup
과 함께 사용하는 핸들러를 설정합니다.
auto popup = new NotificationPopup(&view); profile->setNotificationPresenter([&] (std::unique_ptr<QWebEngineNotification> notification) { popup->present(notification); });
사용자에게 알림 표시하기
이 예의 NotificationPopup
클래스는 알림의 제목, 메시지 및 아이콘을 표시하기 위해 여러 개의 QLabel 인스턴스를 사용하는 간단한 QWidget 기반 클래스입니다.
class NotificationPopup : public QWidget { Q_OBJECT QLabel m_icon, m_title, m_message; std::unique_ptr<QWebEngineNotification> notification;
알림 표시하기
present
메서드 내부에서는 먼저 이전 알림이 있는 경우 이전 알림을 닫고 해제하고 내부 알림 인스턴스에서 std::unique_ptr::swap
메서드를 호출하여 새 알림의 소유권을 가져옵니다.
void present(std::unique_ptr<QWebEngineNotification> &newNotification) { if (notification) { notification->close(); notification.reset(); } notification.swap(newNotification);
그런 다음 QWebEngineNotification::title(), QWebEngineNotification::message(), QWebEngineNotification::icon()를 호출하여 제목, 메시지 및 아이콘에 대한 알림 인스턴스를 쿼리하고 팝업에 적절한 레이블을 설정합니다.
m_title.setText("<b>" + notification->title() + "</b>"); m_message.setText(notification->message()); m_icon.setPixmap(QPixmap::fromImage(notification->icon()).scaledToHeight(m_icon.height()));
그런 다음 QWidget::show() 메서드를 호출하여 사용자에게 알림을 표시할 준비가 되었습니다. 이 단계에서는 QWebEngineNotification::show() 메서드를 호출하여 JavaScript
코드에 쇼 이벤트에 대해 알립니다.
show(); notification->show();
마지막으로 QWebEngineNotification::closed() 신호에 연결하여 JavaScript
쪽에서 닫기 이벤트를 처리하는 콜백을 설정합니다. 또한 타이머 이벤트를 예약하여 활성 알림을 자동으로 닫습니다.
connect(notification.get(), &QWebEngineNotification::closed, this, &NotificationPopup::onClosed); QTimer::singleShot(10000, notification.get(), [&] () { onClosed(); }); }
활성 알림 닫기
시간 초과 또는 JavaScript
이벤트를 처리하여 현재 활성 상태인 알림에 대한 닫기 단계를 실행합니다. 먼저 QWidget::hide()를 호출하여 팝업 위젯 자체를 숨깁니다. 그런 다음 QWebEngineNotification::close() 메서드를 호출하여 JavaScript
코드를 알립니다. 마지막으로 std::unique_ptr::reset()
메서드를 통해 알림 객체를 소멸합니다.
void onClosed() { hide(); notification->close(); notification.reset(); }
사용자 상호작용 구현하기
알림에 대한 클릭 단계를 구현하기 위해 QWidget::mouseReleaseEvent()를 통해 마우스 상호작용을 처리합니다. 이 이벤트에서는 QWebEngineNotification::click() 메서드를 호출하여 JavaScript
코드에 알림을 보냅니다. 그런 다음 알림이 완전히 처리되어 더 이상 필요하지 않은 것으로 간주되므로 자동으로 닫기 단계를 수행하여 파기할 수 있습니다.
void mouseReleaseEvent(QMouseEvent *event) override { QWidget::mouseReleaseEvent(event); if (notification && event->button() == Qt::LeftButton) { notification->click(); onClosed(); } }
© 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.