我正在尝试制作一个qt小部件,它显示一个显示十六进制数字的qlabes表。
我将数字作为qstring传递给标签,准备打印,标签工作正常,但字体类型是系统默认字体(无衬线),具有不同的字母大小,因此包含"A-F“数字的数字不再与其他数字对齐……
我最初使用函数创建字体:
static const QFont getMonospaceFont(){
QFont monospaceFont("monospace"); // tried both with and without capitalized initial M
monospaceFont.setStyleHint(QFont::TypeWriter);
return monospaceFont;
}并创建一个具有此构造函数的自定义QLabel类:
monoLabel(QWidget *parent = 0, Qt::WindowFlags f = 0) : QLabel(parent, f) {
setTextFormat(Qt::RichText);
setFont(getMonospaceFont());
}但是它不起作用,所以我添加到主文件中
QApplication app(argn, argv);
app.setFont(monoLabel::getMonospaceFont(), "monoLabel");同样,字体保持不变。
我在网上搜索QLabel的字体设置问题,但我似乎是唯一一个不能让它们正常工作的人。
我做错了什么??
发布于 2013-09-19 22:32:37
你可能想要一个Monospace风格的提示,而不是Typewriter。下面的代码适用于我在Qt4和5下的OS X。
对于您的应用程序来说,不需要将QLabel设置为富文本。
请注意,QFontInfo::fixedPitch()与QFont::fixedPitch()不同。后者会让您知道是否请求了固定间距的字体。前者表明你是否真的得到了固定间距的字体。

// 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();
}https://stackoverflow.com/questions/18896933
复制相似问题