Qt:更改字体粗细

Mar*_*mar 5 c++ fonts qt qtstylesheets

我想让我的文字QLabel介于粗体和普通风格之间,我相信设置字体粗细应该是我问题的答案。

在 Qt 文档中,我发现有两个选项可以更改字体粗细:

  1. 从 cpp 端通过:QFont::setWeight()接受数字 0-99 的方法

    http://doc.qt.io/qt-4.8/qfont.html#Weight-enum

  2. 从 Qss 样式通过:font-weight属性,它接受数字 100,200,...,900

    http://doc.qt.io/qt-4.8/stylesheet-reference.html#font-weight

我已经尝试了这两种方法,但似乎没有任何效果。我总是只得到普通或普通的大胆风格,而没有介于两者之间。

例子:

QLabel* test1 = new QLabel("Font-weight testing");
test1->show();

QLabel* test2 = new QLabel("Font-weight testing");
QFont font = test2->font();
font.setWeight(40);
test2->setFont(font);
test2->show();

QLabel* test3 = new QLabel("Font-weight testing");
test3->setStyleSheet("font-weight: 400");
test3->show();
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我创建了 3 个标签。一种没有任何额外设置,一种是我通过setWeight方法更改了字体粗细,另一种是应该通过 Qss 样式更改字体粗细。但是这三个最终将完全相同。

我什至试图让字体更大,启用抗锯齿,或使用不同的字体,但没有任何帮助。

han*_*ank 5

QFont::setWeight方法期望其输入值是QFont::Weight枚举值之一。

http://doc.qt.io/qt-5/qfont.html#setWeight

正确的版本:

QLabel* test2 = new QLabel("Font-weight testing");
QFont font = test2->font();
font.setWeight(QFont::Bold);
test2->setFont(font);
Run Code Online (Sandbox Code Playgroud)

QSS 版本中还有两个错误。首先,您没有为规则指定选择器。其次,值 400 对应于“正常”字体。

https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight

正确的版本:

QLabel* test3 = new QLabel("Font-weight testing");
test3->setStyleSheet("QLabel { font-weight: bold; }");
Run Code Online (Sandbox Code Playgroud)


Far*_*had 4

使用setWeight这样的函数:setWeight(QFont::ExtraBold);

QFont font;
font.setWeight(QFont::ExtraBold); // set font weight with enum QFont::Weight
font.setPixelSize(25); // this for setting font size
ui->label->setFont(font);
Run Code Online (Sandbox Code Playgroud)

void QFont::setWeight(int Weight):将字体的粗细设置为weight,该粗细应该是QFont::Weight枚举 中的值。

图像