Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style (rich text) in QListWidgetItem and QCombobox items? (PyQt/PySide)

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

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.

This is what I have:

# 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 )
like image 862
fredrik Avatar asked Mar 07 '14 10:03

fredrik


1 Answers

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)

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

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)

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

like image 66
dorvak Avatar answered Nov 08 '22 06:11

dorvak