0

我创建了这个类来从 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:不能在非本地打印机上使用

4

0 回答 0