[英]How to print textfile with QPrinter
我在樹視圖中有一個文本文件列表(使用QFileSystemModel)。 如果選擇了文本文件並按下了打印按鈕。 它應顯示一個打印對話框,並打印出該文件。 我認為(在閱讀文檔和示例之后)它應該如下所示:
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();
}
重命名部分(因此高於所有打印內容)可以正常工作,沒有任何錯誤或任何錯誤。 但是我在打印錯誤時會出現錯誤。 我以為是因為庫,因為我使用的是Qt5。
#include <QDirModel>
#include <QDebug>
#include <QMessageBox>
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrinter>
#include <QPainter>
#include <QFile>
以下是錯誤:
顯然你正在使用Qt5,其中打印功能被單獨添加(在Qt4中它是QtGui模塊的一部分),請參閱文檔 。 所以你必須添加到pro文件這一行:
QT += printsupport
這將修復您的構建錯誤,但您的代碼尚未打印。 你必須使用painter
。
如果您計划支持Qt4,它應該是這樣的
greaterThan(QT_MAJOR_VERSION, 4) {
QT += printsupport
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.