[英]How to print textfile with QPrinter
I have a list of textfiles in a treeview (with QFileSystemModel). 我在树视图中有一个文本文件列表(使用QFileSystemModel)。 If a textfile is selected and a print button is pressed.
如果选择了文本文件并按下了打印按钮。 It should show a print dialog and the file should be printed out.
它应显示一个打印对话框,并打印出该文件。 I thought (after reading documentations and examples) it should look like this:
我认为(在阅读文档和示例之后)它应该如下所示:
void berichtenhistorie::on_printButton_released()
{
QModelIndex index = ui->treeView->currentIndex();
QFileSystemModel *model = (QFileSystemModel*)ui->treeView->model();
QString path = model->filePath(index);
QString name = model->fileName(index);
QString dir = path;
dir.remove(dir.size() - name.size(), name.size());
QFile file(path);
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
file.close();
if(file.rename(QString("%1geprint %2").arg(dir, name)))
qDebug() << "renamed";
}
//all above works correctly
QPrinter printer(QPrinter::HighResolution);
printer.setPageSize(QPrinter::A4);
printer.setOrientation(QPrinter::Portrait);
printer.setPageMargins (15,15,15,15,QPrinter::Millimeter);
printer.setFullPage(false);
printer.setOutputFileName(path);
printer.setOutputFormat(QPrinter::NativeFormat);
QPainter painter(&printer);
painter.end();
}
The renaming part (so above all the printing stuff) works as it should, no errors or anything. 重命名部分(因此高于所有打印内容)可以正常工作,没有任何错误或任何错误。 But I get abunch of errors at the printing error.
但是我在打印错误时会出现错误。 I thought it was because of the libraries, because im using Qt5.
我以为是因为库,因为我使用的是Qt5。
#include <QDirModel>
#include <QDebug>
#include <QMessageBox>
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrinter>
#include <QPainter>
#include <QFile>
Here are the errors: 以下是错误:
Apparently you are using Qt5, where printing functionality has been placed in separate add on (in Qt4 it is part of QtGui module), see documentation . 显然你正在使用Qt5,其中打印功能被单独添加(在Qt4中它是QtGui模块的一部分),请参阅文档 。 So you have to add to pro file this line:
所以你必须添加到pro文件这一行:
QT += printsupport
This will fix your build error, but your code doesn't print yet. 这将修复您的构建错误,但您的代码尚未打印。 You have to use
painter
. 你必须使用
painter
。
If you are planing to support Qt4 it should be like this 如果您计划支持Qt4,它应该是这样的
greaterThan(QT_MAJOR_VERSION, 4) {
QT += printsupport
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.