QTreeWidget Drag & Drop does not move to top level

Asked 2 years ago, Updated 2 years ago, 455 views

I am using PySide 6.

I made a two-tier tree with QTreeWidget.
When I move my child's QTreeWidgetItem, I want to move only directly below the top level QTreeWidgetItem.

We were able to avoid moving from one child to another, but we couldn't find a way to identify the top-level move (between Data0 and Data1 in this example).

After calling Super class, you can see that you have moved to the top level, but after that, you could not prohibit the movement by calling event.setDropAction (Qt. IgnoreAction).

Is there any good way?

 from PySide 6.QtWidgets import (QTreeWidget, QTreeWidgetItem, QAbstractItemView)


class MyTreeWidget (QTreeWidget):
    def__init__(self, parent=None):
        super(MyTreeWidget,self).__init__(parent)
        self.setDragDropMode(QAbstractItemView.InternalMove)

    def dropEvent(self, event):
        source=event.source()
        pos=event.pos()
        destination_parent=source.itemAt(pos)

        if destination_parent is None:
            print("no parent")
            return

        if destination_parent.parent() is not None:
            print("destination is not top.")
            return

        print("move item")
        super(MyTreeWidget,self).dropEvent(event)


if__name__=="__main__":
    from SetupQt import setup_qt
    from PySide 6.QtWidgets import QApplication

    setup_qt()#forvenv

    app = QApplication()
    widget=MyTreeWidget()

    top_level_items=[]
    for i in range (3):
        item_p = QTreeWidgetItem()
        item_p.setText(0, "Data {0}".format(i))
        for jin range(2):
            item_c=QTreeWidgetItem(item_p)
            item_c.setText(0, "Data {0} {1}.format(i,j))
        top_level_items.append(item_p)

    widget.insertTopLevelItems(0,top_level_items)

    widget.show()
    app.exec()

Your environment is
PySide 6.2.2.1
Python 3.10
That's it.

setup_qt() is a function created to pass the path to Qt into the virtual environment

python pyside

2022-09-30 22:03

1 Answers

My acquaintance solved it for me.
When dragging to the top level, it cannot be placed between items.
When you're in a child's hierarchy, you can only put it between items.

def dropEvent(self, event):
        source=event.source()
        pos=event.pos()
        destination_item=source.itemAt(pos)
        dip=self.dropIndicatorPosition()

        if destination_item.parent() is None and dip!=QAbstractItemView.DropIndicatorPosition.OnItem:
            print("no parent")
            return

        if destination_item.parent() is not None and dip==QAbstractItemView.DropIndicatorPosition.OnItem:
            print("destination is not top.")
            return

        print("move item")
        super(MyTreeWidget,self).dropEvent(event)


2022-09-30 22:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.