6

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.

Fábio Antunes
  • 16,984
  • 18
  • 75
  • 96

1 Answers1

5

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();
}
dom0
  • 7,356
  • 3
  • 28
  • 50
  • Yes, this seems to work. Didn't knew it was required to load Qt GUI components first. Thank you. One more thing (pardon I'm a newcomer to Qt) What you mean by "Note that at least on Linux-based systems the offscreen QPA will not work here."? – Fábio Antunes Oct 05 '14 at 22:39
  • 1
    Qt has the concept of different platforms even on the same operating system. There is e.g. an xcb QPA for normal linux desktop, and eglfs and some others. And then theres `offscreen` which is basically a QPA if you don't have a graphical UI but need QGuiApplication. However, using `-platform offscreen` or `QT_QPA_PLATFORM=offscreen` won't work with this, because it requires some resources that are unavailable (font configuration etc.) with offscreen, at least with Linux. – dom0 Oct 06 '14 at 10:19