I'm creating a folder-tree like structure using QTreeWidget. Each item has 2 columns:
- folder name.
- folder id, which is set to hidden by
tree.hideColumn(1)
.
The goal is to enable drag/drop within the QTreeWidget as well as across widgets, and that requires setting the tree.setDragDropMode(DragDrop)
. However, after changing the mode from InternalMove
to DrapDrop
, I found that the dragged QTreeWidgetItem only has its 1st column retained, the previously existing 2nd column is lost. If I query item.data(1,0)
it gives None
.
If I don't hide the 2nd column, it won't get lost during the drag.
I'm rather confused. Any help is appreciated.
Below is a working example. If you drag any item onto another, the console will print column counts 1
. Same as renaming (double click) a dragged item.
import sys
from PyQt5.QtWidgets import QTreeWidget, QVBoxLayout,\
QMainWindow, QWidget, QTreeWidgetItem, QApplication, QAbstractItemView
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super(self.__class__, self).__init__()
frame=QWidget()
self.setCentralWidget(frame)
hl=QVBoxLayout()
frame.setLayout(hl)
self.tree=QTreeWidget(self)
self.tree.setColumnCount(2)
# if I don't hide 2nd column, it won't get lost during the drag.
self.tree.hideColumn(1)
self.tree.setDragEnabled(True)
# InternalMove gives 2 columns: name and id.
# DragDrop would only give the 1st column after a drag/drop
#self.tree.setDragDropMode(QAbstractItemView.InternalMove)
self.tree.setDragDropMode(QAbstractItemView.DragDrop)
hl.addWidget(self.tree)
# add treewidgetitems
data=[['Folder 1', '1'],
['Folder 2', '2'],
['Folder 3', '3']
]
for ii in range(3):
item=QTreeWidgetItem(data[ii])
self.tree.addTopLevelItem(item)
self.tree.itemDoubleClicked.connect(self.rename)
self.tree.itemChanged.connect(self.postRename, Qt.QueuedConnection)
self.show()
def rename(self):
item=self.tree.selectedItems()
if item:
item=item[0]
item.setFlags(item.flags() | Qt.ItemIsEditable)
self.tree.scrollToItem(item)
self.tree.editItem(item)
def postRename(self,item,column):
print('postRename: column counts', item.columnCount())
text=item.data(0,0)
itemid=item.data(1,0)
print('postRename: item text=',text, 'item id', itemid)
return
if __name__ == "__main__":
app = QApplication(sys.argv)
form = MainWindow()
form.show()
sys.exit(app.exec_())
UserRole
you suggested, and the 2nd column served no other purpose than storing an id. – Jason