如何在 QListWidgetItem 和 QCombobox 项目中设置样式(富文本)?(PyQt/PySide) [英] How to style (rich text) in QListWidgetItem and QCombobox items? (PyQt/PySide)

查看:32
本文介绍了如何在 QListWidgetItem 和 QCombobox 项目中设置样式(富文本)?(PyQt/PySide)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现有人提出了类似的问题,但没有答案或答案是替代解决方案.

I have found similar questions being asked, but without answers or where the answer is an alternative solution.

我需要在 QComboBoxes 和 QListWidgets(在 PySide 中)中创建面包屑路径,并且我正在考虑将这些项目的文本设为粗体.但是,我很难找到有关如何实现这一目标的信息.

I need to create a breadcrumb trail in both QComboBoxes and QListWidgets (in PySide), and I'm thinking making these items' text bold. However, I have a hard time finding information on how to achieve this.

这就是我所拥有的:

# 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 )

推荐答案

你可以使用 html/css-likes 样式,即将你的文本包裹在标签中:

You could use html/css-likes styles, i.e just wrap your text inside tags:

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

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

Another option is setting a font-role:

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

也许你必须在你的情况下使用 QFont.setBold() .但是,使用 html 格式可能更灵活.

Maybe you'd have to use QFont.setBold() in your case. However, using html-formating might be more flexible at all.

在组合框的情况下使用 setItemData():

In the case of a combo-box use 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)

使用样式表格式对 Item-Text 本身不起作用,afaik.

Using style-sheet formating will not work for the Item-Text itself, afaik.

这篇关于如何在 QListWidgetItem 和 QCombobox 项目中设置样式(富文本)?(PyQt/PySide)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆