Search code examples
qtpyqtstylesheetqtreeview

Set bold rows in a QTreeView


I have a custom subclass of a QTreeView in a pyqt application. I'm trying to give the user the ability to highlight and "lowlight" (for lack of a better term) rows. Highlighted rows should have bold text and (optionally) a different background color. Any ideas?
I'm considering StyleSheets as an option, but have so far been unable to get that to work. If I set the QTreeView's stylesheet:

self.setStyleSheet("QTreeView::item:selected {border: 1px solid #567dbc;}")

I can't figure out how to manually enable 'states' that would keep only the desired rows at a particular state. If I try setting an individual item's stylesheet:

#modelIndex is a valid QModelIndex
modelIndex.internalPointer().setStyleSheet()

I get a segfault.
I'm not convinced stylesheets are the way to go, I'm open to all ideas. Thanks!


Solution

  • From what you've said it looks like the easiest solution would be to define a custom item delegate for your treeview and set items font weight to bold whenever it's needed. Pls, check if an example below would work for you, it should create a treeview with custom item delegate which would change item's font style.

    import sys
    from PyQt4 import QtGui, QtCore
    
    class BoldDelegate(QtGui.QStyledItemDelegate):
        def paint(self, painter, option, index):
            # decide here if item should be bold and set font weight to bold if needed 
            option.font.setWeight(QtGui.QFont.Bold)
            QtGui.QStyledItemDelegate.paint(self, painter, option, index)
    
    
    class MainForm(QtGui.QMainWindow):
        def __init__(self, parent=None):
            super(MainForm, self).__init__(parent)
    
            model = QtGui.QStandardItemModel()
    
            for k in range(0, 4):
                parentItem = model.invisibleRootItem()
                for i in range(0, 4):
                    item = QtGui.QStandardItem(QtCore.QString("item %0 %1").arg(k).arg(i))
                    parentItem.appendRow(item)
                    parentItem = item
    
            self.view = QtGui.QTreeView()
            self.view.setModel(model)
            self.view.setItemDelegate(BoldDelegate(self))
    
            self.setCentralWidget(self.view)
    
    def main():
        app = QtGui.QApplication(sys.argv)
        form = MainForm()
        form.show()
        app.exec_()
    
    if __name__ == '__main__':
        main()
    

    hope this helps, regards