Search code examples
c++qtqwebviewqwebkit

How to print using qwebview using qt


When accessing the link from a browser, there is a print button and when you click it the function print will show. And I cannot do this on my program having a qwebview. Im using qt4.7.3 on Ubuntu 11.04.


Solution

  • QWebView has a void print(QPrinter * printer) const method. To show the print dialog, you'd use the QPrintDialog class.

    You need to connect a QAction or some other signal to a slot that shows the print dialog, and another slot to the dialog's accepted signal.

    class MyWindow : public QWidget {
        Q_OBJECT
        QWebView * m_webView;
        QScopedPointer<QPrinter> m_printer;
        ...
        Q_SLOT void showPrintDialog() {
            if (!m_printer) m_printer.reset(new QPrinter);
            QScopedPointer<QPrintDialog> dialog(new QPrintDialog(m_printer.data(), this));
            dialog->setAttribute(Qt::WA_DeleteOnClose);
            connect(dialog.data(), SIGNAL(accepted(QPrinter*)), SLOT(print(QPrinter*)));
            dialog->show();
            dialog.take(); // The dialog will self-delete
        }
        Q_SLOT void print(QPrinter* printer) {
            m_webView->print(printer);
        }
    };