问题
I want to be able to reorder the items in my_tree
and I have somewhat achieved this as follows:
my_tree.setDragEnabled(True)
my_tree.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
my_tree.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
However, I would like to restrict this behaviour only at the same level.
Consider the following toy example:
from PyQt5 import QtWidgets, QtGui, QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
w = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout()
w.setLayout(layout)
self.setCentralWidget(w)
my_tree = QtWidgets.QTreeWidget()
layout.addWidget(my_tree)
alpha = QtWidgets.QTreeWidgetItem(my_tree, ['Alpha'])
beta = QtWidgets.QTreeWidgetItem(my_tree, ['Beta'])
alpha.addChild(QtWidgets.QTreeWidgetItem(['one']))
alpha.addChild(QtWidgets.QTreeWidgetItem(['two']))
beta.addChild(QtWidgets.QTreeWidgetItem(['first']))
beta.addChild(QtWidgets.QTreeWidgetItem(['second']))
my_tree.setDragEnabled(True)
my_tree.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
my_tree.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
my_tree.expandAll()
alpha.child(0).setSelected(True)
self.show()
app = QtWidgets.QApplication([])
window = MainWindow()
app.exec_()
In this example, I would like to only be able to put beta
above alpha
and vice versa. I also want the same thing for each root's child items but only within each root e.g. second
abovefirst
and the opposite.
Nesting should not be allowed (e.g. make two
a child of one
). I also do not want to be able to freely drag children from one root to another nor be able to drag roots within children.
Does anyone have any ideas about how I could approach this?
来源:https://stackoverflow.com/questions/61498439/reorder-items-in-a-tree