我正在尝试实施从QListWidget
到QPlainTextEdit
的拖放功能。
我正在使用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
?
答案 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()