0

PySide6を使用しています。

QTreeWidgetで2階層のTreeを作りました。
子供のQTreeWidgetItemを移動する時、トップレベルのQTreeWidgetItemの直下にしか移動しないようにしたいです。

子供から子供の配下に移動しないようにするのは出来たのですが、トップレベルへの移動(この例で言えば、Data0とData1の間)を識別する手段が見つかりませんでした。

Super classを呼び出した後であれば、トップレベルに移動してしまった事を知ることが出来るのですが、その後で、event.setDropAction(Qt.IgnoreAction)を呼び出す方法では、移動を禁止出来ませんでした。

何か良い手立てはありませんでしょうか。

from PySide6.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 PySide6.QtWidgets import QApplication

    setup_qt()  # for venv

    app = QApplication()
    widget = MyTreeWidget()

    top_level_items = []
    for i in range(3):
        item_p = QTreeWidgetItem()
        item_p.setText(0, "Data{0}".format(i))
        for j in 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()

使用環境は
PySide6 6.2.2.1
Python 3.10
です。

setup_qt()は仮想環境にQtへのパスを通す為に作った関数です

1 件の回答 1

0

知り合いが解決してくれました。
トップレベルにDragする時には、Itemの間には置けなくて、
子供の階層の時には、Itemの間にしか置けないようにしています。

    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)

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。