Reputation: 184
i'm trying to make a qt widget that shows a table of qlabels displaying hex numbers.
i pass the numbers to the labels as qstrings ready to be printed and the labels work properly but the font type is the system default (a sans serif) that has different letter sizes, so the numbers containing "A-F" digits are no more aligned with the other numbers...
i initially create the font with the function:
static const QFont getMonospaceFont(){
QFont monospaceFont("monospace"); // tried both with and without capitalized initial M
monospaceFont.setStyleHint(QFont::TypeWriter);
return monospaceFont;
}
and create a custom QLabel
class that has this constructor:
monoLabel(QWidget *parent = 0, Qt::WindowFlags f = 0) : QLabel(parent, f) {
setTextFormat(Qt::RichText);
setFont(getMonospaceFont());
}
but it doesn't work, so i add to the main file
QApplication app(argn, argv);
app.setFont(monoLabel::getMonospaceFont(), "monoLabel");
and again the font remains unchanged..
i searched the net for font-setting problems with QLabel
s but i seem to be the only one who doesn't get them to work properly..
what am i doing wrong??
Upvotes: 5
Views: 6824
Reputation: 98425
You probably want a Monospace
style hint, not Typewriter
. The following works for me on OS X under Qt 4 and 5.
Setting QLabel to rich text is unnecessary for your application.
Note that QFontInfo::fixedPitch()
is not the same as QFont::fixedPitch()
. The latter lets you know whether you requested a fixed pitch font. The former indicated whether you actually got a fixed pitch font.
// https://github.com/KubaO/stackoverflown/tree/master/questions/label-font-18896933
// This project is compatible with Qt 4 and Qt 5
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#include <QtWidgets>
#endif
bool isFixedPitch(const QFont &font) {
const QFontInfo fi(font);
qDebug() << fi.family() << fi.fixedPitch();
return fi.fixedPitch();
}
QFont getMonospaceFont() {
QFont font("monospace");
if (isFixedPitch(font)) return font;
font.setStyleHint(QFont::Monospace);
if (isFixedPitch(font)) return font;
font.setStyleHint(QFont::TypeWriter);
if (isFixedPitch(font)) return font;
font.setFamily("courier");
if (isFixedPitch(font)) return font;
return font;
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QString text("0123456789ABCDEF");
QWidget w;
QVBoxLayout layout(&w);
QLabel label1(text), label2(text);
label1.setFont(getMonospaceFont());
layout.addWidget(&label1);
layout.addWidget(&label2);
w.show();
return a.exec();
}
Upvotes: 6