Reorder items in a tree

两盒软妹~` 提交于 2020-05-30 16:14:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!