Getting font metrics without a GUI (console mode)

Let's say some images must be generated by the Qt console program and that font metrics are necessary by internal algorithms (they use the text width / height ) as input to calculate the position in which the picture should be). This program should work on Linux without any graphical interface (runlevel-3, basically a cluster without any display server).

Problem: QFontMetrics are only available when starting the Qt application in GUI mode.
Any workaround for getting string metrics without any display server?

+5
source share
1 answer

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

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 using QGuiApplication , this version does not require (does not use) widgets.

See also the example in the documentation on how to handle no cases of gui.


This code works fine 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 using QApplication .

The project file was pretty simple

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

All Articles