웹엔진 위젯 PrintMe 예제
Qt WebEngine 위젯을 사용하여 웹 페이지를 인쇄하는 방법을 보여줍니다.
PrintMe는 QWebEnginePage 및 QPrintDialog 클래스를 사용하여 웹 페이지를 인쇄하는 방법을 보여줍니다. 또한 QPrintPreviewDialog 클래스를 사용하여 인쇄 미리보기를 구현하는 방법을 보여줍니다. 완성도를 높이기 위해 JavaScript 내에서 인쇄 요청을 트리거하는 방법도 설명합니다.
예제 실행하기
에서 예제를 실행하려면 Qt Creator에서 Welcome 모드를 열고 Examples 에서 예제를 선택합니다. 자세한 내용은 예제 빌드 및 실행하기를 참조하세요.
간단한 HTML 페이지
이 예에서는 리소스 컬렉션 파일(.qrc)로 추가되는 내부 HTML 페이지를 만듭니다. 이 페이지에는 키보드 단축키를 사용하거나 버튼을 클릭하여 인쇄를 트리거하는 방법을 설명하는 작은 HTML 메시지 상자만 표시됩니다. 버튼에는 JavaScript window.print()
함수를 호출하는 JavaScript onclick
이벤트 속성이 있습니다.
<html lang="en"> <head> <meta charset="utf-8"> <title>PrintMe</title> <link rel="stylesheet" type="text/css" href="style.css"> <script> function printNow() { window.print(); } </script> </head> <body> <form class="form"> <div class="header"> <h1>Hello Paper World!</h1> <h2>Press Ctrl+p to print with print preview</h2> <h2>Press Ctrl+Shift+p to print without print preview</h2> <h2>Click the button to print using JavaScript</h2> <p class="button" onclick="printNow()">Print Now</p> </div> </form> </body> </html>
주요 기능
main
함수에서는 먼저 QWebEngineView 인스턴스를 인스턴스화하고 내부 HTML 페이지로 URL을 설정합니다. 그런 다음 PrintHandler
인스턴스를 생성하고 요청된 페이지를 전달합니다. 편의를 위해 인쇄 대화 상자 또는 인쇄 미리 보기 대화 상자를 호출하는 데 사용할 수 있는 키보드 단축키도 만듭니다.
QWebEngineView view; view.setUrl(QUrl(QStringLiteral("qrc:/index.html"))); view.resize(1024, 750); view.show(); PrintHandler handler; handler.setView(&view); auto printPreviewShortCut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_P), &view); auto printShortCut = new QShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_P), &view); QObject::connect(printPreviewShortCut, &QShortcut::activated, &handler, &PrintHandler::printPreview); QObject::connect(printShortCut, &QShortcut::activated, &handler, &PrintHandler::print);
인쇄 핸들러
PrintHandler
클래스에서 먼저 printPreview()
을 구현하여 QPrintPreviewDialog 을 인스턴스화합니다. 미리보기 페이지 세트를 생성하려면 QPrintPreviewDialog::paintRequested 핸들이 필요합니다.
void PrintHandler::printPreview() { if (!m_view) return; if (m_inPrintPreview) return; m_inPrintPreview = true; QPrintPreviewDialog preview(&m_printer, m_view); connect(&preview, &QPrintPreviewDialog::paintRequested, this, &PrintHandler::printDocument); preview.exec(); m_inPrintPreview = false; }
이제 QPrintPreviewDialog::paintRequested 신호에 대한 응답으로 호출되는 PrintHandler::printDocument()
슬롯을 구현할 수 있습니다. 프린터에서 실제 페인팅을 수행하려면 QWebEngineView::print() 함수를 호출합니다. 인쇄는 Chromium에서는 비동기 작업이지만 Qt에서는 그렇지 않으므로 QEventLoop::exec()를 사용하여 로컬 이벤트 루프를 실행하여 반환하기 전에 인쇄가 완료되었는지 확인합니다. 인쇄가 완료되기를 기다리는 동안 버튼을 클릭하면 내부 상태가 엉망이 되어 크래시가 발생할 수 있으므로 사용자 입력은 차단됩니다.
void PrintHandler::printDocument(QPrinter *printer) { m_view->print(printer); // User input in the print preview dialog while we're waiting on a print task // can mess up the internal state and cause a crash. m_waitForResult.exec(QEventLoop::ExcludeUserInputEvents); }
인쇄 작업 결과에 대한 알림을 받기 위해 QWebEngineView::printFinished() 신호의 핸들러로 PrintHandler::printFinished()
슬롯을 구현합니다. success
을 확인하고 발생한 오류를 보고합니다. 마지막으로 QEventLoop::quit()를 호출하여 로컬 이벤트 루프를 종료합니다.
void PrintHandler::printFinished(bool success) { if (!success) { QPainter painter; if (painter.begin(&m_printer)) { QFont font = painter.font(); font.setPixelSize(20); painter.setFont(font); painter.drawText(QPointF(10,25), QStringLiteral("Could not generate print preview.")); painter.end(); } } m_waitForResult.quit(); }
마지막으로 구현한 함수 PrintHandler::print()
는 QPrintDialog 을 열고 이전에 구현한 PrintHandler::printDocument()
을 호출하기 때문에 간단합니다.
void PrintHandler::print() { QPrintDialog dialog(&m_printer, m_view); if (dialog.exec() != QDialog::Accepted) return; printDocument(&m_printer); }
© 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.