我想将QGroupBox
的标题变为加粗,而其他保持不变。如何仅更改QGroupBox
标题的字体?
字体属性从父控件继承到子控件,除非被显式设置。你可以通过setFont()
方法改变 QGroupBox
的字体,但是你需要显式地在其子控件上重置字体以打破继承。如果你不想在每个子控件(例如每个QRadioButton
)上单独设置此属性,可以添加一个中间控件,例如:
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);
注意,当为小部件分配新字体时,“从此字体中获取的属性与小部件的默认字体相结合,形成小部件的最终字体”。
更简单的方法是使用样式表-与CSS不同,并且不同于常规字体和颜色继承,样式表中的属性不会被继承:
groupBox->setStyleSheet("QGroupBox { font-weight: bold; } ");
QGroupBox::title
不支持字体属性,因此您无法以此方式设置标题字体。您需要按照上述方法进行设置。setStyleSheet()
方法比使用QFont
更加“简洁”。也就是说,您还可以执行以下操作:groupBox->setStyleSheet("font-weight: bold;");
widget->setStyleSheet("font-weight: normal;");
我搜索的问题来自于PyQt5
而不是直接来自Qt
,因此这里是我的答案,希望它能帮助其他处于与我相同情况的人。
# Set the QGroupBox's font to bold. Unfortunately it transfers to children widgets.
font = group_box.font()
font.setBold(True)
group_box.setFont(font)
# Restore the font of each children to regular.
font.setBold(False)
for child in group_box.children():
child.setFont(font)
至少在Qt 4.8中,使用样式表将字体设置为“bold”对我无效。
一个更简单的版本是将所有子窗口小部件设置为普通字体,这也适用于当您使用Qt Designer(ui文件)时:
QFont fntBold = font();
fntBold.setBold( true );
ui->m_pGroup1->setFont( fntBold );
auto lstWidgets = ui->m_pGroup1->findChildren< QWidget* >();
for( QWidget* pWidget : lstWidgets )
pWidget->setFont( font() );