简体   繁体   中英

Why does QTreeView not fire a Drop or Move event during drag and drop?

I was attempting to figure out an answer to this question when I realized the events I'm looking for aren't occurring.

import sys, new
from PyQt4 import QtGui, QtCore 

class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        self.model = QtGui.QStandardItemModel()

        for k in range(0, 4):
            rootItem = self.model.invisibleRootItem()
            parentItem = QtGui.QStandardItem(QtCore.QString("Parent: %0").arg(k))
            for i in range(0, 5):
                item = QtGui.QStandardItem(QtCore.QString("Value: %0").arg(i))
                parentItem.appendRow(item)
            rootItem.appendRow(parentItem)

        self.view = QtGui.QTreeView()
        self.view.setModel(self.model)
        self.view.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
        self.view.expandAll()
        self.view.installEventFilter(self)
        self.setCentralWidget(self.view)


    def eventFilter(self, object, event):
        if object is self.view:
            if event.type() == QtCore.QEvent.Move:
                print "Moved!"
                event.accept()
                return True
            else:
                event.ignore()
                return super(MainForm, self).eventFilter(object, event)

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

My idea to solve that problem was to utilize an event filter and watch for the QtCore.QEvent.Move event. This is because the DragDrop mode is set to QtGui.QAbstractItemView.InternalMove

The view accepts move (not copy) operations only from itself. - Documentation

The problem is, this event is never fired. Neither is QtCore.QEvent.Drop . Instead I see the following events :

  • QtCore.QEvent.ChildAdded
  • QtCore.QEvent.ChildRemoved
  • QtCore.QEvent.Timer
  • QtCore.QEvent.ToolTip

The drag and drop IS successful. I can move node around as expected. What is happening to the Move or Drop events though?

If I remove the check if object is self.view and just watch for these two events in general, I still don't see them occur.

You need to track events on the viewport, and filter DragMove and Drop :

    self.view.viewport().installEventFilter(self)

def eventFilter(self, object, event):
    if object is self.view.viewport():
        if event.type() == QtCore.QEvent.DragMove:
            print "Moved!"
        elif event.type() == QtCore.QEvent.Drop:
            print "Dropped!"
    return super(MainForm, self).eventFilter(object, event)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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