How to fit the selected color to the cell in QTreeWidget

The length of selected color depends on the length of the string in QTreeWidget of PySide2. How can I fit the length of the cell?

GOAL

To fill the color to fit the size of the cell when the item is selected. (See the article “How to select one column of QTreeWidgetItem in PySide2” to generate an tree widget that allows users to select each item.)

Environment

Windows 10
Python 3.8.7
PySide2 5.15.2

Method

Set show-decoration-selected of qss(QStyleSheet) that can be used for QTreeWidget, QTreeView, QListWidget and QListView.

Controls whether selections in a QListView cover the entire row or just the extent of the text.

from Qt Style Sheets Reference

Use setStyleSheet to set qss to the widget as below.

self.tree_widget.setStyleSheet('QTreeView { show-decoration-selected: 1;}')

See the official documentation “Qt Style Sheets” for details about qss.