QPainter.drawText() SIGSEGV 分割错误

2022-01-12 00:00:00 qt5 printing segmentation-fault c++

我正在尝试通过 Qt5 打印方法在热敏打印机中打印一条简单的文本消息.

I'm trying to print a simple text message in a thermal printer through Qt5 printing methods.

#include <QCoreApplication>
#include <QDebug>
#include <QtPrintSupport/QPrinterInfo>
#include <QtPrintSupport/QPrinter>
#include <QtGui/QPainter>

int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);

   QPrinter printer(QPrinter::ScreenResolution);
   QPainter painter;
   painter.begin(&printer);
   painter.setFont(QFont("Tahoma",8));
   painter.drawText(0,0,"Test");
   painter.end();

   return a.exec();
}

但是,当我通过调试器运行它时,我在 drawText 方法上收到 SIGSEGV Segmentation fault 信号.

However when I run it through the debugger I get a SIGSEGV Segmentation fault signal on the drawText method.

打印机已连接、安装,当我调用 qDebug() <<printer.printerName(); 我得到了应该使用的打印机的正确名称.

The printer is connected, installed and when I call qDebug() << printer.printerName(); I get the correct name of the printer that should be used.

有人知道为什么会抛出这个错误SIGSEGV Segmentation fault"吗?

Anyone knows why is this error being thrown "SIGSEGV Segmentation fault"?

谢谢.

推荐答案

要使 QPrinter 工作,您需要一个 QGuiApplication,而不是 QCoreApplication.

For QPrinter to work you need a QGuiApplication, not a QCoreApplication.

这在 QPaintDevice 文档中有记录:

This is documented in QPaintDevice docs:

警告: Qt 要求 QGuiApplication 对象在创建任何绘图设备之前存在.绘图设备访问窗口系统资源,这些资源在应用程序对象创建之前不会被初始化.

Warning: Qt requires that a QGuiApplication object exists before any paint devices can be created. Paint devices access window system resources, and these resources are not initialized before an application object is created.

请注意,至少在基于 Linux 的系统上,offscreen QPA 在这里不起作用.

Note that at least on Linux-based systems the offscreen QPA will not work here.

#include <QCoreApplication>
#include <QDebug>
#include <QtPrintSupport/QPrinterInfo>
#include <QtPrintSupport/QPrinter>
#include <QtGui/QPainter>
#include <QGuiApplication>
#include <QTimer>

int main(int argc, char *argv[])
{
  QGuiApplication a(argc, argv);

  QPrinter printer;//(QPrinter::ScreenResolution);

  // the initializer above is not the crash reason, i just don't
  // have a printer
  printer.setOutputFormat(QPrinter::PdfFormat);
  printer.setOutputFileName("nw.pdf");

  Q_ASSERT(printer.isValid());

  QPainter painter;
  painter.begin(&printer);
  painter.setFont(QFont("Tahoma",8));
  painter.drawText(0,0,"Test");
  painter.end();

  QTimer::singleShot(0, QCoreApplication::instance(), SLOT(quit()));

  return a.exec();
}

相关文章