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,
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With