PyQt - 拖放



拖放功能对于用户来说非常直观。它存在于许多桌面应用程序中,用户可以将对象从一个窗口复制或移动到另一个窗口。

基于 MIME 的拖放数据传输基于 QDrag 类。QMimeData 对象将其数据与其对应的 MIME 类型关联。它存储在剪贴板上,然后用于拖放过程中。

以下 QMimeData 类函数允许方便地检测和使用 MIME 类型。

测试器 获取器 设置器 MIME 类型
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 另一方面,在放下操作完成时发生。可以有条件地接受或拒绝事件的建议操作。

示例

在以下代码中,DragEnterEvent 验证事件的 MIME 数据是否包含文本。如果是,则接受事件的建议操作,并将文本作为新项目添加到 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()

以上代码产生以下输出:

Drag and Drop Output
广告