从QListWidget拖放到QPlainTextEdit

时间:2014-08-26 12:31:32

标签: python qt events pyqt

我正在尝试实施从QListWidgetQPlainTextEdit的拖放功能。

我正在使用eventFilter但由于某种原因,QPlainTextEdit仅获得Drag个事件。 Drop事件永远不会发生。

源代码:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        widget = QtGui.QWidget(self)
        self.setCentralWidget(widget)
        layout = QtGui.QVBoxLayout(widget)
        self.listA = QtGui.QListWidget(self)
        self.textedit = QtGui.QPlainTextEdit(self)
        self.textedit.installEventFilter(self)
        self.listA.setDragEnabled(True)

        for widget in (self.listA, self.textedit):
            widget.setAcceptDrops(True)
            layout.addWidget(widget)

        for item in 'One Two Three Four Five Six'.split():
            self.listA.addItem(item)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.DragEnter and source is self.textedit):
            event.accept()
            return False
        if (event.type() == QtCore.QEvent.Drop and source is self.textedit):
            print 'Drop'
            return False
        return QtGui.QMainWindow.eventFilter(self, source, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

如何处理Drop事件并将文字更正为QPlainTextEdit

1 个答案:

答案 0 :(得分:2)

根据this example,如果事件已成功过滤,则需要返回True。我其实不确定,但至少下降似乎有效

from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        widget = QtGui.QWidget(self)
        self.setCentralWidget(widget)
        layout = QtGui.QVBoxLayout(widget)
        self.listA = QtGui.QListWidget(self)
        self.textedit = QtGui.QPlainTextEdit(self)
        self.textedit.installEventFilter(self)
        self.listA.setDragEnabled(True)

        for widget in (self.listA, self.textedit):
            widget.setAcceptDrops(True)
            layout.addWidget(widget)

        for item in 'One Two Three Four Five Six'.split():
            self.listA.addItem(item)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.DragEnter and source is self.textedit):
            event.accept()
            print 'DragEnter'
            return True
        elif (event.type() == QtCore.QEvent.Drop and source is self.textedit):
            print 'Drop'
            return True
        else:
            return super(Window, self).eventFilter(source, event)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()