Question

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.

Was it helpful?

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);
    }
};

OTHER TIPS

I used the answer from Kuba Ober and used it in my project as follows:

The .ui file contains a QWebView named 'webView', you can simply create this in QtCreator's Design mode .

Content of .h file

#include <QDialog>
#include <QPrinter>
#include <QPrintDialog>

namespace Ui {
class myclassname;
}

class myclassname : public QDialog
{
    Q_OBJECT

public:
    explicit myclassname(QWidget *parent = 0);
    ~myclassname();

private slots:
    void print(QPrinter* printer);

    void on_pushButton_print_clicked();

private:
    Ui::myclassname *ui;
    QScopedPointer<QPrinter> m_printer;
};

Content of .cpp file

#include "myclassname.h"
#include "ui_myclassname.h"

myclassname::myclassname(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::myclassname)
{
    ui->setupUi(this);
    ui->webView->load(QUrl("https://stackoverflow.com/questions/21260463/how-to-print-using-qwebview-using-qt"));
}

myclassname::~myclassname()
{
    delete ui;
}

void myclassname::print(QPrinter* printer)
{
    ui->webView->print(printer);
}

void myclassname::on_pushButton_print_clicked()
{
    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
}

Thank you @KubaOber

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top