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

问题描述 投票:7回答:2

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

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

qt qt4 console-application fontmetrics
2个回答
3
投票

在收到其他评论后,我想我理解你的问题。就这样做:

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
}

您也可以尝试使用QGuiApplication这个版本不需要(不使用)小部件。

另见example in documentation如何处理无gui案例。


This code works perfectly on my Ubnutu with Qt 5.3
#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;
}

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

项目文件非常简单

QT       += core
TARGET = MetricsNoGui
TEMPLATE = app
SOURCES += main.cpp

0
投票

Qt 4.8有such QApplication构造函数,其第3个参数可以帮助解决问题。简单地提供false作为第三个参数并享受在Qt控制台应用程序中使用QFontMetrics。如果在没有X服务器的系统上启动应用程序,则不会发生崩溃。

© www.soinside.com 2019 - 2024. All rights reserved.