pythonpyqt5qtreewidgetqtreewidgetitem

Partially coloring text of QTreeWidgetItem


I am trying to get part of the text of a QTreeWidgetItem to be set to red and have found a few examples, namely how to set the background color of part of the text in qtreewidgetitem and is it possible to partially italicize the text of a qtreewidgetitem, but they are in C++ so I'm not following them. I get that they're both setting the actual color in the text of a QLabel but am not sure how they're then attributing that to the child item of the tree. I've written up example code to help out.

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        
        self.tree = QtWidgets.QTreeWidget(Form)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.tree.sizePolicy().hasHeightForWidth())
        self.tree.setSizePolicy(sizePolicy)
        self.tree.setMinimumSize(QtCore.QSize(250, 90))
        self.tree.setMaximumSize(QtCore.QSize(250, 90))        
        self.tree.setObjectName("tree")
        self.tree.header().setVisible(False)
        
        rootItem = QtWidgets.QTreeWidgetItem(self.tree)
        rootItem.setText(0, "I AM ROOT")
        
        tempString = "I AM \033[0;31m CHILD \033[0;0m"
        
        mixedLabel = QtWidgets.QLabel()
        mixedLabel.setText(tempString)
        print(mixedLabel.text())
                
        childItem = QtWidgets.QTreeWidgetItem(rootItem)
        self.tree.setItemWidget(childItem, 0, mixedLabel)
        

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

I know the QLabel part is working because the print statement gives me

cmd line output

as I expect, but the actual widget gives me

widget output

where it is not recognizing the ANSI color command. I think I've set up the setItemWidget() call correctly but I could be wrong.


Solution

  • QLabel does not support ANSI color commands. You should use Qt's HTML subset (rich text) instead:

    mixedLabel.setText("I AM <span style='color: red'>CHILD</span>")
    

    Documentation for the capabilities of their HTML subset can be found here: https://doc.qt.io/qt-6/richtext-html-subset.html