QPainter.drawText () SIGSEGV segmentation error

I am trying to print a simple text message in a thermal printer using Qt5 print 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 signal SIGSEGV Segmentation fault

on the method drawText

.

The printer is connected, installed, and when I call qDebug() << printer.printerName();

, I get the correct name of the printer in use.

Does anyone know why this " SIGSEGV Segmentation fault

" error occurs ?

Thank.

+3


source to share


1 answer


For QPrinter

to work you will need QGuiApplication

, not QCoreApplication

.

This is described in the QPaintDevice

docs:

Warning: Qt requires an object to QGuiApplication

exist before any paint devices can be created. Painting devices accessing the window's system resources, and these resources are not initialized until the application object is created.



Note that, at least on Linux based systems, offscreen

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

      

+3


source







All Articles