打印QWebview的文本,QPrintDialog不会出现

时间:2012-04-19 19:53:46

标签: qt qwebview

我试过了:

QPrintDialog printdia(MyWevView);

printdia.exec(); 

QPrinter* printer = printdia.printer();

QPainter painter(printer);      

MyWevView->render(&painter, MyWevView->pos(),MyWevView->visibleRegion());

我知道我不会检查用户是否接受,但这不是问题...每次,我都看不到对话框,只是打印

所以首先我不明白为什么QPrintDialog没有出现,以及为什么它知道我的打印机并直接打印文本

我想解决我的第一个问题将解决我的第二个......

谢谢!

1 个答案:

答案 0 :(得分:2)

以下是使用QWebView进行打印的完整工作示例,QPrintDialog正常工作:

<强> win.h

#ifndef _WIN_H_
#define _WIN_H_

#include <QtGui>
#include <QtWebKit>

class TestWindow : public QMainWindow
{
    Q_OBJECT
    public:
        TestWindow();

    private slots:
        void doPrint();
        void doPrintVis();

    private:
        QWebView* mView;
        Q_DISABLE_COPY(TestWindow)
};

#endif

<强> win.cpp

#include "win.h"

TestWindow::TestWindow() :
    QMainWindow(),
    mView(new QWebView())
{
    setCentralWidget(mView); // Takes ownership

    mView->load(QUrl::fromUserInput("http://qt-project.org/doc/qt-4.8/qwebview.html"));

    QToolBar* tools = addToolBar("Tools");
    QAction* printAction = tools->addAction("Print");
    QAction* printVisAction = tools->addAction("Print Visible");

    connect(printAction, SIGNAL(triggered(bool)), this, SLOT(doPrint()));
    connect(printVisAction, SIGNAL(triggered(bool)), this, SLOT(doPrintVis()));
}

void TestWindow::doPrint()
{
    qDebug() << "TestWindow::doPrint()";

    QPrinter printer;
    QPrintDialog printDlg(&printer);
    if (printDlg.exec() == QDialog::Rejected)
        return;

    mView->print(&printer);
}

void TestWindow::doPrintVis()
{
    qDebug() << "TestWindow::doPrintVis()";

    QPrinter printer;
    QPrintDialog printDlg(&printer);
    if (printDlg.exec() == QDialog::Rejected)
        return;

    QPainter painter(&printer);
    mView->render(&painter, mView->pos(), mView->visibleRegion());
}

<强> TEST.CPP

#include <QtGui>
#include <QtWebKit>

#include "win.h"

int main(int argc, char** argv)
{
    QApplication app(argc, argv);

    TestWindow win;
    win.show();

    return app.exec();
}

<强> test.pro

QT += core gui webkit
SOURCES=test.cpp win.cpp
HEADERS=win.h