Search code examples
pythonqtqtreewidgetitem

How to set the background color of part of the text in QTreeWidgetItem?


For example, the text of QTreeWidgetItem is ["Hello world"], is there any way to set the background color of 'Hello'? The method setBackground seems to set the whole column.


Solution

  • Set a custom Widget as default view of your QTreeWidgetItem, its easy with QLabel. This is an example with a QListWidget and QListWidgetItem:

    QListWidgetItem* MainWindow::addColoredItem(const QString& name, const QColor& backcolor, const QColor& textcolor) {
        QListWidgetItem* item = new QTreeWidgetItem(this);
        QLabel* label = new QLabel(this);
        label->setStyleSheet(QString("QLabel{background: %1; color %2;}").arg(backColor.name(), textColor.name()));
        ui->listWidget->addItem(item);
        ui->listWidget->setItemWidget(item, widget);
        return item;
    }
    

    For QTreeWidgetItem, make the same steps.