获取没有GUI的字体指标(控制台模式)

gpa*_*lex 8 qt qt4 console-application fontmetrics

假设一些图像必须由Qt控制台程序生成,并且内部算法需要字体度量(它们使用文本宽度/高度作为输入来计算绘图应该发生的位置).该程序必须可以在没有任何GUI的Linux上运行(运行级别3,基本上是没有任何显示服务器的集群).

问题: QFontMetrics仅在GUI模式下运行Qt应用程序时可用.
没有任何显示服务器的任何变通方法来获取字符串指标

Mar*_*k R 4

好的,经过补充评论后,我想我理解你的问题。就这样做:

include <QApplication>

int main(int argv, char **args)
{
    QApplication app(argv, args);
    QApplication::processEvents(); // this should allow `QApplication` to complete its initialization

    // do here whatever you need 

    return 0; // or some other value to report errors
}
Run Code Online (Sandbox Code Playgroud)

您还可以尝试使用QGuiApplication此版本不需要(不使用)小部件。

另请参阅文档中如何处理非 GUI 情况的示例。


这段代码在我的带有 Qt 5.3 的 ubnutu 上完美运行

#include <QGuiApplication>
#include <QFontMetrics>
#include <QDebug>

int main(int argc, char *argv[])
{
    QGuiApplication a(argc, argv);

    QFont font("Times", 10, QFont::Bold);
    qDebug() << font;
    QFontMetrics metrics(font);

    qDebug() << metrics.boundingRect("test");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

QApplication使用时它也适用于 Qt 4.8 。

项目文件非常简单

QT       += core
TARGET = MetricsNoGui
TEMPLATE = app
SOURCES += main.cpp
Run Code Online (Sandbox Code Playgroud)

  • 好吧,恐怕我给你赏金的速度太快了!哈哈。它似乎有效,但事实上,如果您取消设置 DISPLAY var env(在调用该程序的终端中),它仍然会崩溃:“QXcbConnection:无法连接到显示\n 中止(核心转储)” (4认同)