Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting font metrics without GUI (console mode)

Let's say some images have to be generated by a Qt console program and that font metrics are needed by internal algorithms (they use the text width/height as input to compute the position where the drawing should occur). This program has to be runable on a Linux without any GUI (runlevel-3, basically a cluster without any display server).

Problem: QFontMetrics are only available when running a Qt application in GUI mode.
Any workaround to get string metrics without any display server ?

like image 894
gpalex Avatar asked Jul 30 '15 19:07

gpalex


1 Answers

Ok after additional comments I think I understand your problem. Just do it like that:

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
}

You can also try use QGuiApplication this version doesn't require (doesn't use) widgets.

See also example in documentation how to handle none gui cases.


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;
}

It also works with Qt 4.8 when QApplication is used.

Project file was quite simple

QT       += core
TARGET = MetricsNoGui
TEMPLATE = app
SOURCES += main.cpp
like image 122
Marek R Avatar answered Nov 18 '22 01:11

Marek R