WebEngine Widgets PrintMe Example

Image non disponible

PrintMe demonstrates how to use the QWebEnginePage and QPrintDialog classes to print a web page. Further, it shows how to implement print preview by using the QPrintPreviewDialog class. For completeness, it also illustrates how to trigger a printing request within JavaScript.

Running the Example

To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example.

Simple HTML Page

In this example, we create an internal HTML page that is added as a resource collection file (.qrc). The page shows only a small HTML message box that explains how to trigger printing by using keyboard shortcuts or clicking a button. The button has the JavaScript onclick event attribute that calls the JavaScript window.print() function.

 
Sélectionnez
<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">
         <img class="logo" src="icon.svg" alt="qtwebengine">
         <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>
      </form>
   </body>
</html>

Main Function

In the main function, we first instantiate a QWebEngineView and set the URL to our internal HTML page. Next, we create a PrintHandler instance and pass the requested page. For convenience, we also create keyboard shortcuts that can be used to call a print dialog or print preview dialog.

 
Sélectionnez
    QWebEngineView view;
    view.setUrl(QUrl(QStringLiteral("qrc:/index.html")));
    view.resize(1024, 750);
    view.show();

    PrintHandler handler;
    handler.setPage(view.page());

    auto printPreviewShortCut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_P), &view);