I am trying to set one QLabel to a monospaced font. By default, I have all my other labels set to "Arame-Regular" in the designer. Normally, trying to set any of my labels to "Arame-Mono" (the monospaced font) in the designer does not work. They stay regular.
After this bit of code in my mainwindow.cpp, every label in the application turns to monospaced:
QFontDatabase::addApplicationFont("/path/to/the/fonts/Arame-Mono.ttf");
QFont monospace("Arame-Mono");
ui->labelFontTest->setFont(monospace);
Which solves part of the problem, a monospaced font is able to be used I guess, but I don't want every label in the application to be set to monospaced. How can I only address this one specific label to apply the monospaced font to it, and keep all other label how they were?
Another side effect of this is I am getting this message on launch:
qt.qpa.fonts: Populating font family aliases took 159 ms. Replace uses of missing font family "Arame-Mono" with one that exists to avoid this cost.
I both have the fonts installed locally on my Mac and added to my .pro file. The fonts are inside the fonts folder inside the project directory:
DISTFILES += \
Fonts/Arame-Mono.ttf \
Fonts/Arame-Regular.ttf \
Any help appreciated!
I've created a simple demo; it shows three labels where only the last one is set manually to monospace:
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
using QFD = QFontDatabase;
if (QFD::addApplicationFont(QStringLiteral(":/Roboto/Roboto-Regular.ttf")) == -1) {
qWarning() << "Failed to load Roboto-Regular.ttf";
}
if (QFD::addApplicationFont(QStringLiteral(":/Roboto_Mono/RobotoMono-Regular.ttf")) == -1) {
qWarning() << "Failed to load RobotoMono-Regular.ttf";
}
QFont regular("Roboto");
QApplication::setFont(regular);
MainWindow w;
w.show();
return a.exec();
}
QFont mono("RobotoMono");
ui->label_3->setFont(mono);
This works flawlessly. In your case, I suggest in the main
to set the regular font for the application. Then only when needed use the monospace one. Also, remember that if you plan to ship the application you should embed the fonts in the executable using a QtResources (.qrc
) file.