Qt:改变字体粗细

时间:2017-11-23 12:27:10

标签: c++ qt fonts qtstylesheets

我希望QFont::setWeight()中的文字介于粗体和普通样式之间,我相信设置字体粗细应该是我问题的答案。

在Qt文档中,我发现有两种选择如何更改字体粗细:

  1. 从cpp侧通过:font-weight方法接受数字0-99

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

  2. 从Qss样式到: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(); 属性,接受数字100,200,...,900

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

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

    示例:

    setWeight

    在上面的示例中,我创建了3个标签。一个没有任何额外设置,一个是通过typeid(T) == typeid(const T)方法改变字体粗细的一个,另一个是通过Qss样式改变字体粗细的设置。但这三个人最终会完全一样。

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

2 个答案:

答案 0 :(得分:1)

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);

此外,您在QSS版本中有两个错误。首先,您没有为规则指定选择器。其次,400的值对应于' normal'字体。

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

正确的版本:

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

答案 1 :(得分:0)

使用功能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);

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

image

相关问题