【问题标题】:How to style (rich text) in QListWidgetItem and QCombobox items? (PyQt/PySide)如何在 QListWidgetItem 和 QCombobox 项目中设置样式(富文本)? (PyQt/PySide)
【发布时间】:2014-03-07 10:45:05
【问题描述】:

我发现有人问过类似的问题,但没有答案或答案是替代解决方案。

我需要在 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 )

【问题讨论】:

    标签: python pyqt pyside


    【解决方案1】:

    您可以使用 html/css-likes 样式,即将您的文本包装在标签内:

    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)
    

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

    【讨论】:

    • 它不在我希望设置文本样式的数据中,而是在每个项目的实际可见文本中; QComboBox.addItem() 和 QListWidgetItem.setText()。对不起,如果我不清楚。我尝试按照您对这个可见文本的建议进行操作,但这似乎不起作用。
    • item.setFont(QtGui.QFont('Verdana', bold=True)) 似乎适用于 QListWidgetItem,但我无法让它与 QComboBox.addItem() 一起使用,因为我无法在 str 上执行 setFont。有什么想法吗?
    • 查看我的编辑;)这对我有用(把它放在你的循环中)
    • 另一种实现粗体的方法:QtGui.QFont('Tahoma', 8, QtGui.QFont.Bold)
    猜你喜欢
    • 2014-05-12
    • 2012-01-15
    • 1970-01-01
    • 2011-04-15
    • 2015-05-11
    • 2017-04-03
    • 2015-12-22
    • 1970-01-01
    相关资源
    最近更新 更多