更新时间:2022-05-06 20:09:10
QMimeData 类具有处理丢弃 url 的方法.下面是一个最小的工作示例:
The QMimeData class has methods for dealing with dropped urls. Below is a minimal working example:
# from PyQt4.QtGui import QApplication, QLabel
# from PySide2.QtWidgets import QApplication, QLabel
from PyQt5.QtWidgets import QApplication, QLabel
class Window(QLabel):
def __init__(self):
super().__init__()
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
print('drag-enter')
if event.mimeData().hasUrls():
print('has urls')
event.accept()
else:
event.ignore()
def dropEvent(self, event):
lines = []
for url in event.mimeData().urls():
lines.append('dropped: %r' % url.toLocalFile())
self.setText('
'.join(lines))
app = QApplication(['Drag & Drop'])
window = Window()
window.setGeometry(50, 100, 400, 300)
window.show()
app.exec_()
更新:
关于问题的补充:
一些小部件(与上面使用的 QLabel
不同)有一个默认的 dragMoveEvent
实现,它明确地忽略大多数事件.例如,基于 QAbstractItemView
的类可能只处理某些类型的内部移动而忽略其他所有内容.在这种情况下,应添加重新实现 dragMoveEvent
以明确接受需要以不同方式处理的事件:
Some widgets (unlike the QLabel
used above) have a default implementation of dragMoveEvent
that explicitly ignores most events. For example, classes based on QAbstractItemView
may only handle certain kinds of internal move and ignore everything else. In which case, a reimplementation of dragMoveEvent
should be added that explicitly accepts the events that need to be handled differently:
class MyView(QTableView):
...
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
super().dragMoveEvent(event)