Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qml: platform independent way for Monospace/Normal font

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,

like image 737
Hyndrix Avatar asked Oct 15 '25 10:10

Hyndrix


2 Answers

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.

like image 145
Mitch Avatar answered Oct 17 '25 00:10

Mitch


Another way to do this is to use the Markdown feature. A Markdown code block will be printed monospace in that case. E.g.:

Label {
  textFormat: Text.MarkdownText
  text: '```\n' + my_actual_text + '\n```'
}

No context or extensions required, but the downside is that you may accidentally have some stuff in your content that would get formatted weirdly in Markdown.

like image 37
Sander Vocke Avatar answered Oct 17 '25 01:10

Sander Vocke