3

Is there a way to switch the font.family between "normal" and "monospace" in Qml in a platform independent way?

Label {
   font.family: "Monospace"
}

At the moment I set the font for each platform independently. Shipping a font with the application is also no option because the text is very likely in the system's language (for instance the user interface is English but the text might be in Parsi).

Regards,

Hyndrix
  • 4,282
  • 7
  • 41
  • 82

1 Answers1

2

It appears that the accepted answer for this question works, so you could expose that font to QML as a context property:

main.cpp:

#include <QApplication>
#include <QFontDatabase>
#include <QQmlApplicationEngine>
#include <QQmlContext>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QFont fixedFont = QFontDatabase::systemFont(QFontDatabase::FixedFont);
    engine.rootContext()->setContextProperty("fixedFont", fixedFont);
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));

    return app.exec();
}

main.qml:

import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Controls 2.0

Window {
    width: 400
    height: 400
    visible: true

    Switch {
        id: monospaceSwitch
    }

    Text {
        text: "Hello World"
        font: monospaceSwitch.checked ? fixedFont : Qt.application.font
        anchors.centerIn: parent
    }
}

This assumes that a monospace font exists on the system.

Community
  • 1
  • 1
Mitch
  • 23,716
  • 9
  • 83
  • 122
  • ``QFontDatabase::systemFont(QFontDatabase::FixedFont)`` does not return a fixed font (it returns "Segoe UI" for instance when the "qtquickcontrols2.conf" file is set to Style=Universal and another non-fixed font when using material design). But this might be a Qt bug. – Hyndrix Apr 30 '17 at 16:29
  • Btw: A monotype font exists on the system ("Courier New"). – Hyndrix Apr 30 '17 at 16:30
  • Sounds like a bug? – Mitch Apr 30 '17 at 19:22