如何在QListWidgetItem和QComboBox项中设置(富文本)样式?(PyQt/PySide)

7

我发现有类似的问题被提出,但是没有答案或者答案是另一种解决方案。

我需要在QComboBoxes和QListWidgets(在PySide中)中创建面包屑导航,并且我想让这些项的文本加粗。然而,我很难找到如何实现这一点的信息。

这是我目前拥有的:

# QComboBox
for server in servers:
    if optionValue == 'top secret':
        optionValue = server
    else:
        optionValue = '<b>' + server + '</b>'
    self.comboBox_servers.addItem( optionValue, 'data to store for this QCombobox item' )


# QListWidgetItem
for folder in folders:
    item = QtGui.QListWidgetItem()
    if folder == 'top secret':
        item.setText( '<b>' + folder + '</b>' )
    else:
        item.setText( folder )
    iconSequenceFilepath = os.path.join( os.path.dirname(__file__), 'folder.png' )
    item.setIcon( QtGui.QIcon(r'' + iconSequenceFilepath + ''))
    item.setData( QtCore.Qt.UserRole, 'data to store for this QListWidgetItem' )
    self.listWidget_folders.addItem( item )
1个回答

7
你可以使用类似于HTML/CSS的样式,即只需将文本包裹在标签中即可:


item.setData( QtCore.Qt.UserRole, "<b>{0}</b>".format('data to store for this QListWidgetItem'))

另一个选项是设置字体角色:

item.setData(0, QFont("myFontFamily",italic=True), Qt.FontRole)

也许你需要在你的情况下使用QFont.setBold()。然而,使用HTML格式可能更加灵活。
对于组合框,请使用setItemData():
# use addItem or insertItem (both works)
# the number ("0" in this case referss to the item index)
combo.insertItem(0,"yourtext"))
#set at tooltip
combo.setItemData(0,"a tooltip",Qt.ToolTipRole)
# set the Font Color
combo.setItemData(0,QColor("#FF333D"),Qt.BackgroundColorRole)
#set the font
combo.setItemData(0, QtGui.QFont('Verdana', bold=True), Qt.FontRole)

使用样式表格式化将不适用于项目文本本身,据我所知。

2
我希望样式化的文本不是在数据中,而是在每个项目的实际可见文本中;QComboBox.addItem() 和 QListWidgetItem.setText()。如果我之前表述不清楚,那我很抱歉。我尝试了你建议的方法来处理这个可见文本,但好像不起作用。 - fredrik
1
item.setFont(QtGui.QFont('Verdana', bold=True)) 似乎可以用于 QListWidgetItem,但我无法在 QComboBox.addItem() 上使用此方法,因为我不能对字符串执行 setFont。有什么想法吗? - fredrik
看我的修改 ;) 这对我有效(将此放在您的循环内部) - dorvak
1
另一种实现字体加粗的方法是:QtGui.QFont('Tahoma', 8, QtGui.QFont.Bold) - fredrik

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