【问题标题】:Print the text in C++ using Qt creator使用 Qt creator 在 C++ 中打印文本
【发布时间】:2016-12-21 08:45:26
【问题描述】:

在 Qt Creator 中使用 C++ 作为语言我创建了一个记事本(与 Microsoft Windows 的简单文本编辑器相同,它是一个基本的文本编辑程序)但我找不到将其打印选项保存为的确切代码图像或 pdf 文件并打印在创建的记事本中写入的内容。编写的代码给出了一个错误提示

...\NotePad\mainwindow.cpp:5: error: QPrinter: No such file or directory
 #include <QPrinter>

代码编写

#include <QPrinter>
void MainWindow::on_actionPrint_triggered()
{
    QPrinter printer(QPrinter::HighResolution);
    printer.setOutputFileName("print.ps");
    painter.end();
}

【问题讨论】:

  • 知道错误不与我们分享是不是有点残忍? “给出错误”无助于解决您的问题。 painter.end() 也是有意的,是实际代码中的错字还是这里的错字?
  • 编辑问题
  • 如果找不到 QPrinter 包含文件,请查看此链接是否有帮助:stackoverflow.com/questions/19145763/…

标签: c++ qt printing qt-creator


【解决方案1】:

您可以将QTextDocument 用于类似的简单打印任务。假设您已将文本加载到其中,您可以执行以下操作(我以打印到 pdf 为例,您可以在任何地方打印):

QTextDocument doc; // your text is here
QPrinter printer;
printer.setOutputFileName("<your_file_name_goes_here");
printer.setOutputFormat(QPrinter::PdfFormat);
doc.print(&printer);
printer.newPage(); // this might not be necessary if you want just 1 page, I'm not sure

如果你想使用 QPainter,你应该

QPrinter printer;
// setup the printer
QPainter painter;

if(!painter.begin(&printer))
{
   // return, throw exception, whatever
}
painter.drawText(10, 10, "your_text");
printer.newPage(); // Again, this might not be necessary if you want just 1 page, I'm not sure
painter.end();

【讨论】:

  • @Chum_ChumZy,它在 (10,10) 坐标的位置绘制“your_text”。 QPrinter 派生自 QPaintDevice,因此您可以使用 QPainger 在其上绘画,就像在其他任何东西上打印一样(例如 QImage)。
  • 你介意解释一下painter.drawText(10, 10, "your_text");意思是?我正在寻找打印选项代码 fyi :)
  • 我想打印使用 Qt 创建的记事本中所写的内容。不是控制台显示的内容:)
  • @Chum_ChumZy,它与控制台无关...如果您想了解更多信息,您应该阅读有关 QPainter 的文档。对于您的情况,QTextDocument 的第一个示例就足够了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
相关资源
最近更新 更多