Pyqt 简明教程
PyQt - Drag & Drop
提供 drag and drop 对用户来说非常直观。它存在于许多桌面应用程序中,用户可以在其中将对象从一个窗口复制或移动到另一个窗口。
The provision of drag and drop is very intuitive for the user. It is found in many desktop applications where the user can copy or move objects from one window to another.
基于 MIME 的拖放数据传输基于 QDrag 类。 QMimeData 对象将数据与其对应的 MIME 类型相关联。它存储在剪贴板上,然后用于拖放过程。
MIME based drag and drop data transfer is based on QDrag class. QMimeData objects associate the data with their corresponding MIME type. It is stored on clipboard and then used in the drag and drop process.
以下 QMimeData 类函数允许方便地检测和使用 MIME 类型。
The following QMimeData class functions allow the MIME type to be detected and used conveniently.
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。另一方面,部件应响应拖放事件,以存储拖到其中的数据。
Many QWidget objects support the drag and drop activity. Those that allow their data to be dragged have setDragEnabled() which must be set to true. On the other hand, the widgets should respond to the drag and drop events in order to store the data dragged into them.
-
DragEnterEvent provides an event which is sent to the target widget as dragging action enters it.
-
DragMoveEvent is used when the drag and drop action is in progress.
-
DragLeaveEvent is generated as the drag and drop action leaves the widget.
-
DropEvent, on the other hand, occurs when the drop is completed. The event’s proposed action can be accepted or rejected conditionally.
Example
在以下代码中,DragEnterEvent 验证事件的 MIME 数据是否包含文本。如果包含,则接受事件的提议操作,并将文本作为一个新项目添加到 ComboBox 中。
In the following code, the DragEnterEvent verifies whether the MIME data of the event contains text. If yes, the event’s proposed action is accepted and the text is added as a new item in the ComboBox.
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore 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 & drop')
def main():
app = QApplication(sys.argv)
ex = Example()
ex.show()
app.exec_()
if __name__ == '__main__':
main()
上述代码生成以下输出 -
The above code produces the following output −