如何仅更改QGroupBox标题的字体?

14

我想将QGroupBox的标题变为加粗,而其他保持不变。如何仅更改QGroupBox标题的字体?

4个回答

19

字体属性从父控件继承到子控件,除非被显式设置。你可以通过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; } ");

这个方法对话框标题也适用吗?谢谢。 - user1899020
非常有指导性的答案。非常感谢!!!我认为这种方式也适用于对话框标题。太棒了!!! - user1899020
1
我刚试了一下,它没有立即起作用,所以我不确定是否可以完成 - 至少如果它是顶级窗口/对话框,则本地窗口系统可能会阻止修改字体。也许这可以帮助:http://www.qtcentre.org/threads/25974-stylesheet-to-QDialog-Title-Bar - Andreas Fester
明白了。非常感谢! - user1899020
样式表没有被继承,太棒了。救命稻草。 - quimnuss

2
以上回答是正确的。 以下是一些额外的细节,这可能会有所帮助:
1)我在使用样式表设置QGroupBox标题字体大小中学到,QGroupBox::title不支持字体属性,因此您无法以此方式设置标题字体。您需要按照上述方法进行设置。
2)我发现setStyleSheet()方法比使用QFont更加“简洁”。也就是说,您还可以执行以下操作:
groupBox->setStyleSheet("font-weight: bold;");
widget->setStyleSheet("font-weight: normal;");

2

我搜索的问题来自于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)

0

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接