QPainter.drawText() SIGSEGV Segmentation fault

爷,独闯天下 提交于 2021-02-07 14:28:34

问题


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();
}

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

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

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

Thank you.


回答1:


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

This is documented in QPaintDevice docs:

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.

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();
}


来源:https://stackoverflow.com/questions/26205461/qpainter-drawtext-sigsegv-segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!