我正在尝试在我的应用程序中实现拖放,但是从不调用目标小部件中的dropEvent
。
我搜索了很多这个问题,但是我发现的每个解决方案都涉及重写dragMoveEvent
,我做到了,但没有区别。
由于上述原因,我的示例代码也不起作用:
主窗口类:
class Win(QtWidgets.QWidget):
def __init__(self):
super(Win, self).__init__()
self.setGeometry(200, 300, 400, 200)
self.setLayout(QtWidgets.QHBoxLayout())
self.layout().addWidget(DragLabel())
self.layout().addWidget(DropTest())
要拖动的标签:
class DragLabel(QtWidgets.QLabel):
def __init__(self):
super(DragLabel, self).__init__()
self.setText("Drag me")
def mouseMoveEvent(self, e):
if e.buttons() != QtCore.Qt.LeftButton:
return
mimeData = QtCore.QMimeData()
mimeData.setText("Test drop")
drag = QtGui.QDrag(self)
drag.setMimeData(mimeData)
dropAction = drag.exec(QtCore.Qt.CopyAction)
要放到的小部件:
class DropTest(QtWidgets.QWidget):
def __init__(self):
super(DropTest, self).__init__()
self.setAcceptDrops(True)
def dragEnterEvent(self, e):
print("DragEnter")
e.accept()
def dragMoveEvent(self, e):
print("DragMove")
e.accept()
def dropEvent(self, e):
print("DropEvent")
position = e.pos()
print(position)
e.accept()
[当我将标签拖动到另一个小部件上时,我看到dragEnterEvent
和dragMoveEvent
都在被调用,但是当我实际上放下标签时,dropEvent
函数没有消息。
此外,关闭窗口后,应用程序将挂起并且不会退出。
我正在Fedora 31中使用DNF安装的PyQt 5.13.1x86_64。Python版本是3.7.5,没有virtualenv。
尝试:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class DropTest(QtWidgets.QLabel): # - QWidget + QLabel
def __init__(self):
super(DropTest, self).__init__()
self.setAcceptDrops(True)
self.setText(" Accept Drops")
self.setStyleSheet("QLabel { background-color : #ccd; color : blue; font-size: 20px;}")
def dragEnterEvent(self, e):
# print("DragEnter")
e.accept()
def dragMoveEvent(self, e):
# print("DragMove")
e.accept()
def dropEvent(self, e):
# print("DropEvent")
# position = e.pos()
# print(position)
self.setText(e.mimeData().text()) # +++
e.setDropAction(Qt.MoveAction) # +++
e.accept()
class DragLabel(QtWidgets.QLabel):
def __init__(self):
super(DragLabel, self).__init__()
self.setText("Drag me")
def mouseMoveEvent(self, e):
if e.buttons() != QtCore.Qt.LeftButton:
return
mimeData = QtCore.QMimeData()
mimeData.setText(self.text()) # ("Test drop")
drag = QtGui.QDrag(self)
drag.setMimeData(mimeData)
dropAction = drag.exec(QtCore.Qt.CopyAction)
class Win(QtWidgets.QWidget):
def __init__(self):
super(Win, self).__init__()
self.setGeometry(200, 300, 400, 200)
self.setLayout(QtWidgets.QHBoxLayout())
self.layout().addWidget(DragLabel())
self.layout().addWidget(DropTest())
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Win()
w.show()
sys.exit(app.exec_())