【问题标题】:Qt: change font weightQt:更改字体粗细
【发布时间】:2018-05-07 10:11:52
【问题描述】:

我希望我的文本在 QLabel 介于粗体和普通样式之间,我相信设置 font-weight 应该是我的问题的答案。

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

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

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

【问题讨论】:

  • 您是否安装了中等粗细字体,或者您希望系统通过魔术来生成它们?
  • 我真的不知道

标签: c++ qt fonts qtstylesheets


【解决方案1】:

像这样使用函数setWeightsetWeight(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 枚举的值。

【讨论】:

    【解决方案2】:

    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的值对应“普通”字体。

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

    正确的版本:

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

    【讨论】:

    • 我对粗体字没有意见。我无法获得中等重量的字体结果。即使没有 QLabel 选择器,font-weight: bold; 也能正常工作
    猜你喜欢
    • 1970-01-01
    • 2013-07-24
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 2014-07-16
    相关资源
    最近更新 更多