2

我有一个简单的 TreeWidget,其中填充了子类 TreeWidgetItems。当这些项目之一通过内部拖放事件移动时,我如何捕捉被移动的项目?

当项目被移动时,我想抓住这个项目,这样我就可以得到它的新父项目。

我尝试使用 eventFilter 来查找 ChildRemoved 事件,但是当我为孩子询问事件时,它返回一个通用 QObject,而不是我的子类项目。我错过了什么?

def eventFilter(self, sender, event):
    if event.type() == QtCore.QEvent.ChildRemoved:
        widgetItemThatMoved = event.child()
        self.updateSomething(widgetItemThatMoved)
    return False

谢谢!

4

1 回答 1

1

你需要实现一个dragEnterEvent、dragMoveEvent和dropEvent

要访问丢弃的 QTreeWidgetItem(s),您可以在 dropEvent 中执行此操作

class myTreeWidget(QtGui.QTreeWidget):
    def __init__(self, parent = None):
        super(myTreeWidget, self).__init__(parent)
        self.setAcceptDrops(True)


    def dragEnterEvent(self, event):
        print('dragEnterEvent happened')
        event.acceptProposedAction()

    def dragMoveEvent(self, event):
        print('dragMoveEvent happened')
        event.acceptProposedAction()

    def dropEvent(self, event):
        print('dropEvent happened')
        widgetItemThatMoved=event.source().currentItem()
        parentThatReceivedIt=self.itemAt(event.pos())
        self.theFunc(parentThatReceivedIt,widgetItemThatMoved )
        event.acceptProposedAction()

    def functionToCallWhenDropped(self,theFunc):
        #this method allows you to pass a reference to this class so you assign it to a local variable for easy calling.
        self.theFunc=theFunc

最好添加一个额外的方法 functionToCallWhenDropped 以便您可以访问父类方法,在父类中,您将执行类似这样的操作

 def someMethod(self):
        self.tw=myTreeWidget(parent)
        self.tw.functionToCallWhenDropped(self.wasDropped)

    def wasDropped(self, newParent, theMovedChild):
        #this method will be called the very moment you drop the item
        print(newParent.text(0)+" => "+theMovedChild.text(0))

我希望这可以帮助别人。

于 2013-06-20T07:27:38.337 回答