pythonqtpyside2qtreewidgetqtreewidgetitem

Customize QTreeWidgetItem Pyside2


I have a QTreeWidget where I want each row to be like this widget:

enter image description here

I know how to create the widget itself, how to create a basic QTreeWidgetItem but I don't know how to tie the both of them together.

I am using PySide2 and python.


Solution

  • Without any Minimal Reproducible Example and If I andertood your question you can try something like that.

    It create an item and in each column you can assign a text or another widget.

    from PySide2 import QtWidgets, QtCore, QtGui
    
    class Window(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(Window, self).__init__(parent=parent)
    
            layout = QtWidgets.QVBoxLayout()
    
            self.treewidget = QtWidgets.QTreeWidget()
            self.treewidget.setColumnCount(4)
    
            layout.addWidget(self.treewidget)
    
            self.setLayout(layout)
    
            self.build_tree()
    
    
        def build_tree(self):
            for index in range(10):
                item = QtWidgets.QTreeWidgetItem(self.treewidget)
                item.setText(0, 'icon 1')
                item.setText(1, 'icon 2')
    
                line_edit = QtWidgets.QLineEdit(self.treewidget)
    
                push_button = QtWidgets.QPushButton(self.treewidget)
                push_button.setText('TEST')
    
                self.treewidget.setItemWidget(item, 2, line_edit)
                self.treewidget.setItemWidget(item, 3, push_button)
    
    
    app = QtWidgets.QApplication([])
    window = Window()
    window.show()
    app.exec_()
    

    And if you don't want to have more than one column in your treewidget, I think you can use a Qwidget and a layout like this (just replace the method).

    def build_tree(self):
       for index in range(10):
       item = QtWidgets.QTreeWidgetItem(self.treewidget)
    
       widget = QtWidgets.QWidget()
       layout = QtWidgets.QHBoxLayout()
    
       label_1 = QtWidgets.QLabel('icon 1')
       label_2 = QtWidgets.QLabel('icon 2')
       line_edit = QtWidgets.QLineEdit()
       push_button = QtWidgets.QPushButton('TEST')
    
       layout.addWidget(label_1)
       layout.addWidget(label_2)
       layout.addWidget(line_edit)
       layout.addWidget(push_button)
    
       widget.setLayout(layout)
    
       self.treewidget.setItemWidget(item, 0, widget)
    

    and remove this line in the init method:

    self.treewidget.setColumnCount(4)