简体   繁体   English

如何使用自定义dropEvent编码禁用拖放时的QTreeWidget插入?

[英]How to disable QTreeWidget insertion on drag and drop, with coding custom dropEvent?

I have the following code and i want disable drag and drop in between QTreeWidgetItem existing in the tree.我有以下代码,我想禁用树中存在的 QTreeWidgetItem 之间的拖放。 I can not figure out how?我想不通怎么办? Any thoughts?有什么想法吗?

def dropEvent(self, event):
    target_item = self.itemAt(event.pos())
    if not target_item:
        return

    selected_items = self.selectedItems()
    item = None
    if selected_items:
        for item in selected_items:
            item_data = item.data(0, QtCore.Qt.UserRole)
            target_item_data = target_item.data(0, QtCore.Qt.UserRole)

            if components_api.is_plug(item.text(0)):
                if components_api.is_plug(target_item.text(0)):
                    return
            else:
                if not components_api.is_plug(item.text(0)):
                    if not components_api.is_part_root(item.text(0)):
                        return
                if not components_api.is_plug(target_item.text(0)):
                    return
            item.setExpanded(True)
    super(TreeWidget, self).dropEvent(event)

In simple cases, if no special implementation has been made, this should suffice:在简单的情况下,如果没有进行特殊实现,这应该足够了:

class TreeWidget(QtWidgets.QTreeWidget):
    def __init__(self, parent=None):
        super(TreeWidget, self).__init__(parent)
        # ...
        self.setDragDropOverwriteMode(True)
        self.setDragDropMode(self.InternalMove)

Otherwise, you just can ignore the event if the drop indicator is not on the item, after processing the dragMove event using the base class implementation.否则,在使用基本 class 实现处理 dragMove 事件之后,如果项目上没有放置指示器,则可以忽略该事件。 Since the drop indicator should be shown to ensure a successful drag/drop operation and you probably don't want it visible if the operation should be ignored, you can enable it before calling the base implementation and then disable it afterwards accordingly:由于应该显示放置指示器以确保成功的拖放操作,并且如果应该忽略该操作,您可能不希望它可见,因此您可以在调用基本实现之前启用它,然后相应地禁用它:

    def dragMoveEvent(self, event):
        self.setDropIndicatorShown(True)
        super(TreeWidget, self).dragMoveEvent(event)
        if self.dropIndicatorPosition() != self.OnItem:
            self.setDropIndicatorShown(False)
            event.ignore()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM