[英]Qt QFont selection of a monospace font doesn't work
我正在嘗試制作一個qt小部件,顯示一個顯示十六進制數字的qlabels表。
我將數字傳遞給標簽,因為qstrings准備打印並且標簽正常工作但字體類型是系統默認值(無襯線字體),具有不同的字母大小,因此包含“AF”數字的數字不再與其他數字......
我最初使用函數創建字體:
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
的字體設置問題,但我似乎是唯一沒有讓它們正常工作的人..
我究竟做錯了什么??
你可能想要一個Monospace
風格的提示,而不是Typewriter
。 以下適用於Qt 4和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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.