如何在Cpp中为Qml创建打印助手

时间:2019-01-08 12:12:47

标签: qml qprinter

我已经创建了此类以从qml打印pdf文件,执行时给我错误,单击某些按钮后出现错误(“我的qml文件很大,所以我没有共享它”),无论如何都没有问题从qml文件执行程序,甚至执行cpp代码的第一行。错误说明和代码:

我的头文件:

#ifndef PRINTERHELPER_H
#define PRINTERHELPER_H

#include <QObject>

class PrinterHelper : public QObject
{
    Q_OBJECT
public:
    explicit PrinterHelper(QObject *parent = nullptr);

public:
Q_INVOKABLE void print(QString data);

signals:

public slots:
};

#endif // PRINTERHELPER_H

我的cpp文件:

#include "printerhelper.h"
#include <QtPrintSupport/QPrinter>
#include <QPainter>
#include <QtPrintSupport/QPrintDialog>
#include <QPixmap>
#include <QImage>
#include <qdebug.h>
PrinterHelper::PrinterHelper(QObject *parent) : QObject(parent)
{

}
void  PrinterHelper::print(QString filename)
{
    qDebug()<<"Print file name is "<<filename;
    QPrinter printer(QPrinter::HighResolution);
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName(filename);
    QPrintDialog *dlg = new QPrintDialog(&printer,0);
    dlg->setWindowTitle(QObject::tr("Print Document"));

    if(dlg->exec() == QDialog::Accepted) {
        QPainter painter;
        if (! painter.begin(&printer)) { // failed to open file
            qWarning("failed to open file, is it writable?");
            return;
        }
    }
    delete dlg;

}

Qml代码:

MouseArea{
       anchors.fill: parent
       onClicked: {                                  
           PRINT.print(file_directory+file_name)
       }
}

错误是:

Print file name is  "C:/PishkhanTemp/saham_edalat/se_20190108150150.pdf"
QWidget: Cannot create a QWidget without QApplication
Debug Error!

Program: C:\QtN\Qt5.12.0\5.12.0\msvc2017\bin\Qt5Cored.dll
Module: 5.12.0
File: kernel\qwidget.cpp
Line: 1126

QWidget: Cannot create a QWidget without QApplication

,我已经更改为#include <QApplication >
更新: 错误: QPrintDialog:不能在非本机打印机上使用

0 个答案:

没有答案