How to change the font of a QGroupBox's title only?

Font properties are inherited from parent to child, if not explicitly set. You can change the font of the QGroupBox through its setFont() method, but you then need to break the inheritance by explicitly resetting the font on its children. If you do not want to set this on each individual child (e.g. on each QRadioButton) separately, you can add an intermediate widget, e.g. something like

QGroupBox *groupBox = new QGroupBox("Bold title", parent);

// set new title font
QFont font;
font.setBold(true);
groupBox->setFont(font);

// intermediate widget to break font inheritance
QVBoxLayout* verticalLayout = new QVBoxLayout(groupBox);
QWidget* widget = new QWidget(groupBox);
QFont oldFont;
oldFont.setBold(false);
widget->setFont(oldFont);

// add the child components to the intermediate widget, using the original font
QVBoxLayout* verticalLayout_2 = new QVBoxLayout(widget);

QRadioButton *radioButton = new QRadioButton("Radio 1", widget);
verticalLayout_2->addWidget(radioButton);

QRadioButton *radioButton_2 = new QRadioButton("Radio 2", widget);
verticalLayout_2->addWidget(radioButton_2);

verticalLayout->addWidget(widget);

Note also, when assigning a new font to a widget, "the properties from this font are combined with the widget's default font to form the widget's final font".


An even easier approach is to use style sheets - unlike with CSS, and unlike the normal font and color inheritance, properties from style sheets are not inherited:

groupBox->setStyleSheet("QGroupBox { font-weight: bold; } ");

Tags:

Qt