【问题标题】:Using QPainter with QCoreApplication将 QPainter 与 QCoreApplication 一起使用
【发布时间】:2019-08-26 13:36:27
【问题描述】:

我们有一个应用程序 (QCoreApplication),它接受一些图像作为输入,对它们执行一些操作,然后再次导出它们。我们现在需要向图像添加一些文本,并尝试使用 QPainter 类来完成。在我们的其他应用之一(使用 QApplication)中使用它时一切正常,但在我们的主 QCoreApplication 应用中却没有。

代码如下:

void drawTextOnImage(QImage* image, const QString& text, const QFont& font)
{
    QPainter p;
    if (!p.begin(image)) return;

    p.setFont(font);
    p.drawText(image->rect(), Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, text);

    p.end();
}

应用程序在drawText 行崩溃。

有什么想法吗?

这是一个非常简单的文本,所以不使用 Qt 的建议也会受到重视。

【问题讨论】:

  • QCoreApplication 是控制台应用程序的基类。无法将 QCoreApplication 与小部件一起使用(并且 QPainter 或 QImage 取决于小部件)。您需要改用 QApplication。
  • 您可能会尝试在QPixmap 上而不是在QImage 上绘画。 IE。将您的功能更改为:void drawTextOnImage(const QPixmap &image, const QString& text, const QFont& font)
  • @markus-nm QPainter 不依赖于小部件,它不需要QApplication,而是需要QGuiAppication

标签: c++ qt


【解决方案1】:

当使用来自“Qt Gui”的类时,比如QPainter,你应该使用QGuiApplication,而不是QCoreApplication

您可能会很幸运,并且能够在仅使用 QCoreApplication 的情况下制作一些 GUI 内容。但正如您所发现的,它使您的应用程序非常脆弱。像QPixmap 这样的一些类会打印一条错误消息,但其他类只会崩溃。

同样适用于“Qt Widget”:如果你使用一个widget相关的类,你必须使用QApplication

请注意,由于QApplication 继承QGuiApplication,如果您有QApplication,则可以使用“Qt Gui”。

【讨论】:

    【解决方案2】:

    如果您需要在没有窗口系统的情况下运行非 GUI 应用程序,除了创建 QGuiApplication 的实例之外,您还需要选择合适的 Qt 平台。

    对我来说,offscreen 平台运行良好。我正在生成带有文本元素的图像并将它们保存到无头 Raspberry Pi 上的文件中。我的代码就像下面的例子。请注意,setenv 是一个 POSIX 函数,可能需要在 Windows 上进行替换,但我不确定是否是无窗口 Windows。

    #include <stdlib.h>
    #include <QImage>
    #include <QPainter>
    #include <QGuiApplication>
    
    int main(int argc, char** argv)
    {
        setenv("QT_QPA_PLATFORM","offscreen",1);
        QGuiApplication app(argc,argv);
    
        QImage img(128,128, QImage::Format_RGB888);
        img.fill(Qt::white);
        QPainter p(&img);
        p.drawText(QPoint(0,64), "Works!");
        img.save("/tmp/test.png");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多