2014-10-05 56 views
3

我试图通过QT5打印方法热敏打印机打印一个简单的文本消息。QPainter.drawText()SIGSEGV段错误

#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信号。

打印机连接,安装,当我打电话qDebug() << printer.printerName();我得到应使用打印机的正确名称。

任何人都知道为什么被抛出这个错误“SIGSEGV Segmentation fault”?

谢谢。

回答

3

对于QPrinter工作,你需要一个QGuiApplication,而不是QCoreApplication

这是记录在QPaintDevice文档:

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

请注意,至少在基于Linux的系统上,offscreen QPA在此处不起作用。

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

是的,这似乎工作。不知道它需要首先加载Qt GUI组件。谢谢。还有一件事(原谅我初来乍到的Qt),您可以通过“请注意,至少在基于Linux的系统屏幕外QPA不会在这里工作。”是什么意思? – 2014-10-05 22:39:10

+1

即使在同一个操作系统上,Qt也拥有不同平台的概念。有例如普通Linux桌面的xcb QPA,以及eglfs和其他一些。如果你没有图形用户界面但是需要QGuiApplication,那么这个'offscreen'基本上就是QPA。然而,使用'-platform offscreen'或'QT_QPA_PLATFORM = offscreen'不会有这方面的工作,因为它需要一些资源不可用(字体配置等)的屏幕外,至少有Linux操作系统。 – dom0 2014-10-06 10:19:30