简体   繁体   中英

Qt: change font weight

I would like to have my text in QLabel somewhere between bold and normal style and I believe that setting font-weight should be the answer to my problem.

In Qt documentation, I have found out that there are two options how to change font-weight:

  1. From cpp side via: QFont::setWeight() method which accepts numbers 0-99

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

  2. From Qss style via: font-weight attribute, which accepts numbers 100,200,...,900

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

I have tried both methods and nothing seems to work. I always get only normal or the ordinary bold style and nothing in between.

Example:

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

In the example above, I have created 3 labels. One without any additional setting, one where I have changed font weight via setWeight method, and one where the font-weight should be changed via Qss style. But all three will end up being exactly the same.

I have even tried to make font bigger, enable antialiasing, or use different font but nothing helped.

The QFont::setWeight method expects its input value to be one of the QFont::Weight enum values.

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

The correct version:

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

Also you have two errors in the QSS version. First, you didn't specify a selector for your rule. Second, the value of 400 corresponds to 'normal' font.

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

The correct version:

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

Use function setWeight like this: 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): Sets the weight the font to weight, which should be a value from the QFont::Weight enumeration.

图片

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM