gpt4 book ai didi

c++ - QPainter.drawText() SIGSEGV 段错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:34:31 26 4
gpt4 key购买 nike

我正在尝试通过 Qt5 打印方法在热敏打印机中打印一条简单的文本消息。

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

然而,当我通过调试器运行它时,我得到一个 SIGSEGV Segmentation fault drawText 上的信号方法。

打印机已连接、安装,当我调用 qDebug() << printer.printerName(); 时我得到了应该使用的打印机的正确名称。

任何人都知道为什么会抛出此错误“SIGSEGV Segmentation fault”?

谢谢。

最佳答案

要使 QPrinter 正常工作,您需要一个 QGuiApplication,而不是 QCoreApplication

这在 QPaintDevice 文档中有记录:

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.

请注意,至少在基于 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();
}

关于c++ - QPainter.drawText() SIGSEGV 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26205461/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com