How to select one column of QTreeWidgetItem in PySide2
GOAL
To allow users to select one column from the QTreeWidget as below. (If you’d like to know how to generate tree widget, check “How to use QTreeWidget() in PySide2” first.)
Environment
Windows 10
Python 3.8.7
PySide2 5.15.2
Method
Use SelectionBehavior.
At first, I create a QTreeWidget as below. When a item is selected, the all items in other column of the row at once by default.
import sys from PySide2.QtWidgets import * class MyMainWindow(QMainWindow): def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) self._generateUI() self._tree_widget_multicolumn() def _generateUI(self): main_widget = QWidget() main_layout = QVBoxLayout() main_widget.setLayout(main_layout) self.setCentralWidget(main_widget) self.tree_widget = QTreeWidget() main_layout.addWidget(self.tree_widget) def _tree_widget_multicolumn(self): headers = ["header1", "header2", "header3"] self.tree_widget.setHeaderLabels(headers) tree_widget_item1 = QTreeWidgetItem(["items1_col1", "items1_col2", "items1_col3"]) tree_widget_item1.addChild(QTreeWidgetItem(["items1_1_col1", "items1_1_col2", "items1_1_col3"])) tree_widget_item1.addChild(QTreeWidgetItem(["items1_2_col1", "items1_2_col2"])) tree_widget_item1.addChild(QTreeWidgetItem(["items1_3_col1", "items1_3_col2", "items1_3_col3"])) self.tree_widget.addTopLevelItem(tree_widget_item1) tree_widget_item2 = QTreeWidgetItem(["items2_col1", "items2_col2"]) self.tree_widget.addTopLevelItem(tree_widget_item2) tree_widget_item2.addChild(QTreeWidgetItem(["items2_1_col1", "items2_1_col2", "items2_1_col3"])) def launch(): app = QApplication.instance() if not app: app = QApplication(sys.argv) widget = MyMainWindow() widget.show() app.exec_() launch()
Then set SelectionBehavior to the tree view with function setSelectionBehavior() to select only one column of the item. If you’d like to allow users to select single item (1 column and 1 row).
self.tree_widget.setSelectionBehavior(QAbstractItemView.SelectItems)
You can also set to select only column and rows.
#This is default self.tree_widget.setSelectionBehavior(QAbstractItemView.SelectRows)
self.tree_widget.setSelectionBehavior(QAbstractItemView.SelectColumns)
If you set QAbstractItemView.SelectColumns, you can select items at the same level that have same parent of the tree at once.
How to get selected column
You can get the selected column with currentIndex() regardless of the current SelectionBehavior.
current_col = self.tree_widget.currentIndex().column() print(current_col) # output is 0, 1, or 2 in the above case