Pyqt5 简明教程
PyQt5 - Drag and Drop
提供 drag and drop 对用户来说非常直观。它存在于许多桌面应用程序中,用户可以在其中将对象从一个窗口复制或移动到另一个窗口。
基于 MIME 的拖放数据传输基于 QDrag 类。 QMimeData 对象将数据与其相应的 MIME 类型相关联。这些对象存储在剪贴板上,然后用于拖放过程中。
以下 QMimeData 类函数允许方便地检测和使用 MIME 类型。
Tester |
Getter |
Setter |
MIME Types |
hasText() |
text() |
setText() |
text/plain |
hasHtml() |
html() |
setHtml() |
text/html |
hasUrls() |
urls() |
setUrls() |
text/uri-list |
hasImage() |
imageData() |
setImageData() |
image/ * |
hasColor() |
colorData() |
setColorData() |
application/x-color |
许多 QWidget 对象支持拖放活动。允许拖拽其数据的对象已设置 setDragEnabled(),它必须设置为 true。另一方面,部件应响应拖放事件,以存储拖到其中的数据。
-
DragEnterEvent 提供一个事件,该事件会在拖拽操作进入目标部件时发送给目标部件。
-
在拖放操作进行中时,将使用 DragMoveEvent 。
-
当拖放操作离开部件时,将生成 DragLeaveEvent 。
-
另一方面, DropEvent 发生在放置完成后。可以有条件地接受或拒绝事件的提议操作。
Example
在以下代码中, DragEnterEvent 验证事件的 MIME 数据是否包含文本。如果是,则接受事件的建议操作并将文本作为 ComboBox 中的新项进行添加。
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class combo(QComboBox):
def __init__(self, title, parent):
super(combo, self).__init__( parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, e):
print (e)
if e.mimeData().hasText():
e.accept()
else:
e.ignore()
def dropEvent(self, e):
self.addItem(e.mimeData().text())
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
lo = QFormLayout()
lo.addRow(QLabel("Type some text in textbox and drag it into combo box"))
edit = QLineEdit()
edit.setDragEnabled(True)
com = combo("Button", self)
lo.addRow(edit,com)
self.setLayout(lo)
self.setWindowTitle('Simple drag and drop')
def main():
app = QApplication(sys.argv)
ex = Example()
ex.show()
app.exec_()
if __name__ == '__main__':
main()
上述代码生成以下输出 -