Reputation: 1
I am tyring to put together a QTreeWidget UI that uses custom widgets as its items. I want to be able to drag and drop to rearrange the items in the tree. I am finding that, on drop, the custom widgets are getting lost. How can I make this work? Thanks.
Simplified code example below:
from PySide6 import QtWidgets, QtCore
class CustomWidgetItem(QtWidgets.QWidget):
def __init__(self, label_text, parent=None):
super(CustomWidgetItem, self).__init__(parent)
self.layout = QtWidgets.QHBoxLayout(self)
self.label = QtWidgets.QLabel(label_text)
self.button = QtWidgets.QPushButton("Custom Button")
self.button.clicked.connect(self.btn_click)
self.layout.addWidget(self.label)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
def btn_click(self):
print(self.label.text())
class CustomTreeWidget(QtWidgets.QTreeWidget):
def __init__(self, parent=None):
super(CustomTreeWidget, self).__init__(parent)
self.setHeaderHidden(True)
self.setDragEnabled(True)
self.setDragDropMode(QtWidgets.QTreeView.InternalMove)
def dropEvent(self, event):
source = event.source()
if isinstance(source, QtWidgets.QTreeWidget):
super().dropEvent(event)
else:
event.setDropAction(QtCore.Qt.MoveAction)
event.accept()
class MainWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle("Custom Tree Widget")
self.layout = QtWidgets.QVBoxLayout(self)
self.tree_widget = CustomTreeWidget()
self.layout.addWidget(self.tree_widget)
self.add_items()
def add_items(self):
for i in range(5):
child_item = QtWidgets.QTreeWidgetItem(self.tree_widget, ['Group %d' % i])
custom_widget_item = QtWidgets.QTreeWidgetItem(child_item)
custom_widget = CustomWidgetItem('Item %d' % i)
# set widget
self.tree_widget.setItemWidget(custom_widget_item, 0, custom_widget)
if __name__ == '__main__':
app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
app.exec()
Upvotes: 0
Views: 213