如何获取Drop发生的项目

时间:2014-08-12 20:41:25

标签: python pyqt

以下代码会创建包含五个项目的QTreeWidget

enter image description here

我想知道如何获取内部拖放后发生丢弃的项目(或其索引)。假设我选择“ Item_4 ”,然后将其拖放到“ Item_2 ”。它是“Item_2”我想得到(收到被删除项目的项目)。

0. startDrag(): <PyQt4.QtCore.DropActions object at 0x10f5d1230>
1. dragEnterEvent(): <PyQt4.QtGui.QDragEnterEvent object at 0x10f5cb6d8> 
2. dropEvent(): <PyQt4.QtGui.QDropEvent object at 0x10f5cb6d8> 
3. startDrag(): <PyQt4.QtCore.DropActions object at 0x10f5d1230>

======

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

class Tree(QtGui.QTreeWidget):
    def __init__(self, *args, **kwargs):
        super(Tree, self).__init__()
        self.setDragDropMode(self.DragDrop)
        for each in ['Item_1','Item_2','Item_3','Item_4','Item_5']:
            item=QtGui.QTreeWidgetItem([each])
            self.addTopLevelItem(item)
        self.setColumnCount(1)
        self.resize(360,240)
        self.show()
    def startDrag(self, actions):
        print '0. startDrag(): %s'%actions        
        super(Tree, self).startDrag(actions)
        print '3. startDrag(): %s \n'%actions
    def dragEnterEvent(self, event):        
        super(Tree, self).dragEnterEvent(event)
        print '1. dragEnterEvent(): %s'%event
    def dropEvent(self, event):
        super(Tree, self).dropEvent(event)
        print '2. dropEvent(): %s'%event
tree=Tree()
sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

您可以使用QPoint pos (self)课程中的QDropEvent与位置目的地的QTreeWidgetItem QTreeWidget.itemAt (self, QPoint p) QTreeWidgetItem一起实施;

.
.
def dragMoveEvent (self, eventQDragMoveEvent):
    QtGui.QTreeWidget.dragMoveEvent(self, eventQDragMoveEvent)
    sourceQCustomTreeWidget = eventQDragMoveEvent.source()
    if isinstance(sourceQCustomTreeWidget, QtGui.QTreeWidget):
        print '#############'
        sourceQTreeWidgetItem = sourceQCustomTreeWidget.currentItem()
        if sourceQTreeWidgetItem != None:
            print 'Source :', sourceQTreeWidgetItem.text(0)
        else:
            print 'Source : None'
        destinationQTreeWidgetItem = self.itemAt(eventQDragMoveEvent.pos())
        if destinationQTreeWidgetItem != None:
            print 'Destination :', destinationQTreeWidgetItem.text(0)
        else:
            print 'Destination : None'
.
.

QTreeWidgetItem QTreeWidget.itemAt (self, QPoint p)参考

http://pyqt.sourceforge.net/Docs/PyQt4/qtreewidget.html#itemAt

QPoint QDropEvent.pos (self)参考

http://pyqt.sourceforge.net/Docs/PyQt4/qdropevent.html#pos


此致