2014-10-05 61 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