mel*_*ica 4 c++ fonts qt qlabel qfont
我正在尝试制作一个 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;
}
Run Code Online (Sandbox Code Playgroud)
并创建一个QLabel具有此构造函数的自定义类:
monoLabel(QWidget *parent = 0, Qt::WindowFlags f = 0) : QLabel(parent, f) {
setTextFormat(Qt::RichText);
setFont(getMonospaceFont());
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用,所以我添加到主文件中
QApplication app(argn, argv);
app.setFont(monoLabel::getMonospaceFont(), "monoLabel");
Run Code Online (Sandbox Code Playgroud)
再次字体保持不变..
我在网上搜索了QLabels 的字体设置问题,但我似乎是唯一一个没有让它们正常工作的人。
我究竟做错了什么??
您可能想要一个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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5031 次 |
| 最近记录: |