pyqt5 qtreewidgetitem enable drop drag

Solutions on MaxInterview for pyqt5 qtreewidgetitem enable drop drag by the best coders in the world

showing results for - "pyqt5 qtreewidgetitem enable drop drag"
Emmaline
16 Apr 2018
1import sys
2from PyQt5 import QtCore, QtGui, QtWidgets
3
4IDRole = QtCore.Qt.UserRole + 1000
5
6class MainWindow(QtWidgets.QMainWindow):
7    def __init__(self):
8        super(self.__class__, self).__init__()
9
10        self.tree = QtWidgets.QTreeWidget(columnCount=1,
11            dragDropMode=QtWidgets.QAbstractItemView.DragDrop,
12            dragEnabled=True)
13        self.tree.hideColumn(1)
14
15        self.tree.itemDoubleClicked.connect(self.rename)
16        self.tree.itemChanged.connect(self.postRename)
17
18        # add treewidgetitems
19        data=[['Folder 1', '1'],
20              ['Folder 2', '2'],
21              ['Folder 3', '3']
22              ]
23        for d in data:
24            text, itemid = d
25            item = QtWidgets.QTreeWidgetItem([text])
26            item.setData(0, IDRole, itemid)
27            self.tree.addTopLevelItem(item)
28
29        frame = QtWidgets.QWidget()
30        self.setCentralWidget(frame)
31        hl = QtWidgets.QVBoxLayout(frame)
32        hl.addWidget(self.tree)
33
34    @QtCore.pyqtSlot()
35    def rename(self):
36        item=self.tree.selectedItems()
37        if item:
38            item=item[0]
39            item.setFlags(item.flags() | Qt.ItemIsEditable)
40            self.tree.scrollToItem(item)
41            self.tree.editItem(item)
42
43    @QtCore.pyqtSlot(QtWidgets.QTreeWidgetItem, int)
44    def postRename(self, item, column):
45        print('postRename: column counts', item.columnCount())
46        text = item.text(0)
47        itemid = item.data(0, IDRole)
48        print('postRename: item text=',text, 'item id', itemid)
49
50if __name__ == "__main__":
51     app = QtWidgets.QApplication(sys.argv)
52     form = MainWindow()
53     form.show()
54     sys.exit(app.exec_())
55