【发布时间】:2014-01-21 14:09:14
【问题描述】:
从浏览器访问链接时,有一个打印按钮,当您单击它时,将显示功能打印。我不能在我的程序上有一个 qwebview 做到这一点。我在 Ubuntu 11.04 上使用 qt4.7.3。
【问题讨论】:
从浏览器访问链接时,有一个打印按钮,当您单击它时,将显示功能打印。我不能在我的程序上有一个 qwebview 做到这一点。我在 Ubuntu 11.04 上使用 qt4.7.3。
【问题讨论】:
QWebView 有一个void print(QPrinter * printer) const 方法。要显示打印对话框,您可以使用 QPrintDialog 类。
您需要将QAction 或其他一些信号连接到显示打印对话框的插槽,并将另一个插槽连接到对话框的accepted 信号。
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);
}
};
【讨论】:
我使用了the answer from Kuba Ober,在我的项目中使用如下:
.ui 文件包含一个名为“webView”的 QWebView,您可以在 QtCreator 的设计模式中简单地创建它。
.h 文件的内容
#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;
};
.cpp 文件的内容
#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
}
谢谢@KubaOber
【讨论】:
ui->webView->setStyleSheet("background-color: white"); 来解决,就在 ui->webView->load(QUrl... 行之前