python3+PyQt5重新实现自定义数据拖放处理


Posted in Python onApril 19, 2018

本文分成两部分,第一部分通过python3+PyQt5实现自定义数据的拖放操作。第二部分则对第一部分的程序进行修改,增加拖放操作时,菜单提示是否移动或拷贝,还有可以通过ctrl键盘来设置移动过程中拷贝源而非会将源删除。

自定义数据MIME数据类型QMimeData,MIME是一种用于处理具有多个组成部分的自定义数据的标准化格式。MIME数据由一个数据类型和一个子类型构成?例如,text/plain,text/html,image/png,要处理自定义MIME数据,就必须要选用一种自定义数据类型和一种子类型,然后将数据封装到QMimeData对象中。本例子中,我们创建端为application/x-icon-and-text类型的新MIME数据。

注:

dragEnterEvent这是一个拖拽事件的函数,我们把文件拖拽进程序界面打开,之前必须setAcceptDrops(true)了以后拖拽,但是只设置acceptDrops还不够,还需要在dragEnterEvent事件中对拖入的对象进行筛选,判断mimeData的类型是否是你能处理的,如果是,则调用event.acceptProposedAction()放行。拖放结束后会产生dropEvent事件,在那里进行最后的放置操作。总之这是拖拽事件函数的一个筛选事件并放置的函数。

第一部分:

#!/usr/bin/env python3
import os
import sys
from PyQt5.QtCore import (QByteArray, QDataStream, QIODevice, QMimeData,
  QPoint, QSize, Qt)
from PyQt5.QtWidgets import (QApplication, QDialog,QGridLayout,
        QLineEdit, QListWidget,QListWidgetItem, QWidget)
from PyQt5.QtGui import QIcon,QColor,QPainter,QFontMetricsF,QDrag

class DropLineEdit(QLineEdit):

 def __init__(self, parent=None):
  super(DropLineEdit, self).__init__(parent)
  self.setAcceptDrops(True)


 def dragEnterEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.accept()
  else:
   event.ignore()


 def dragMoveEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.setDropAction(Qt.CopyAction)
   event.accept()
  else:
   event.ignore()


 def dropEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   data = event.mimeData().data("application/x-icon-and-text")
   stream = QDataStream(data, QIODevice.ReadOnly)
   text = ""
   #stream >> text
   text=stream.readQString()
   self.setText(text)
   event.setDropAction(Qt.CopyAction)
   event.accept()
  else:
   event.ignore()


class DnDListWidget(QListWidget):

 def __init__(self, parent=None):
  super(DnDListWidget, self).__init__(parent)
  self.setAcceptDrops(True)
  self.setDragEnabled(True)


 def dragEnterEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.accept()
  else:
   event.ignore()


 def dragMoveEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.setDropAction(Qt.MoveAction)
   event.accept()
  else:
   event.ignore()


 def dropEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   data = event.mimeData().data("application/x-icon-and-text")
   stream = QDataStream(data, QIODevice.ReadOnly)
   text = ""
   icon = QIcon()
   #stream >> text >> icon
   text=stream.readQString()
   stream >> icon
   item = QListWidgetItem(text, self)
   item.setIcon(icon)
   event.setDropAction(Qt.MoveAction)
   event.accept()
  else:
   event.ignore()


 def startDrag(self, dropActions):
  item = self.currentItem()
  icon = item.icon()
  data = QByteArray()
  stream = QDataStream(data, QIODevice.WriteOnly)
  #stream << item.text() << icon
  stream.writeQString(item.text())
  stream << icon
  mimeData = QMimeData()
  mimeData.setData("application/x-icon-and-text", data)
  drag = QDrag(self)
  drag.setMimeData(mimeData)
  pixmap = icon.pixmap(24, 24)
  drag.setHotSpot(QPoint(12, 12))
  drag.setPixmap(pixmap)
  if drag.exec(Qt.MoveAction) == Qt.MoveAction:
   self.takeItem(self.row(item))


class DnDWidget(QWidget):

 def __init__(self, text, icon=QIcon(), parent=None):
  super(DnDWidget, self).__init__(parent)
  self.setAcceptDrops(True)
  self.text = text
  self.icon = icon


 def minimumSizeHint(self):
  fm = QFontMetricsF(self.font())
  if self.icon.isNull():
   return QSize(fm.width(self.text), fm.height() * 1.5)
  return QSize(34 + fm.width(self.text), max(34, fm.height() * 1.5))


 def paintEvent(self, event):
  height = QFontMetricsF(self.font()).height()
  painter = QPainter(self)
  painter.setRenderHint(QPainter.Antialiasing)
  painter.setRenderHint(QPainter.TextAntialiasing)
  painter.fillRect(self.rect(), QColor(Qt.yellow).lighter())
  if self.icon.isNull():
   painter.drawText(10, height, self.text)
  else:
   pixmap = self.icon.pixmap(24, 24)
   painter.drawPixmap(0, 5, pixmap)
   painter.drawText(34, height,
        self.text + " (Drag to or from me!)")


 def dragEnterEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.accept()
  else:
   event.ignore()


 def dragMoveEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.setDropAction(Qt.CopyAction)
   event.accept()
  else:
   event.ignore()


 def dropEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   data = event.mimeData().data("application/x-icon-and-text")
   stream = QDataStream(data, QIODevice.ReadOnly)
   self.text = ""
   self.icon = QIcon()
   #stream >> self.text >> self.icon
   self.text=stream.readQString()
   stream>>self.icon

   event.setDropAction(Qt.CopyAction)
   event.accept()
   self.updateGeometry()
   self.update()
  else:
   event.ignore()


 def mouseMoveEvent(self, event):
  self.startDrag()
  QWidget.mouseMoveEvent(self, event)


 def startDrag(self):
  icon = self.icon
  if icon.isNull():
   return
  data = QByteArray()
  stream = QDataStream(data, QIODevice.WriteOnly)
  #stream << self.text << icon
  stream.writeQString(self.text)
  stream<<icon
  mimeData = QMimeData()
  mimeData.setData("application/x-icon-and-text", data)
  drag = QDrag(self)
  drag.setMimeData(mimeData)
  pixmap = icon.pixmap(24, 24)
  drag.setHotSpot(QPoint(12, 12))
  drag.setPixmap(pixmap)
  drag.exec(Qt.CopyAction)


class Form(QDialog):

 def __init__(self, parent=None):
  super(Form, self).__init__(parent)

  dndListWidget = DnDListWidget()
  path = os.path.dirname(__file__)
  for image in sorted(os.listdir(os.path.join(path, "images"))):
   if image.endswith(".png"):
    item = QListWidgetItem(image.split(".")[0].capitalize())
    item.setIcon(QIcon(os.path.join(path,
         "images/{0}".format(image))))
    dndListWidget.addItem(item)
  dndIconListWidget = DnDListWidget()
  dndIconListWidget.setViewMode(QListWidget.IconMode)
  dndWidget = DnDWidget("Drag to me!")
  dropLineEdit = DropLineEdit()

  layout = QGridLayout()
  layout.addWidget(dndListWidget, 0, 0)
  layout.addWidget(dndIconListWidget, 0, 1)
  layout.addWidget(dndWidget, 1, 0)
  layout.addWidget(dropLineEdit, 1, 1)
  self.setLayout(layout)

  self.setWindowTitle("Custom Drag and Drop")

if __name__ == "__main__":
 app = QApplication(sys.argv)
 form = Form()
 form.show()
 app.exec_()

运行结果:

python3+PyQt5重新实现自定义数据拖放处理

第二部分:

#!/usr/bin/env python3
import os
import sys
from PyQt5.QtCore import (QByteArray, QDataStream, QIODevice, QMimeData,
  QPoint, QSize, Qt)
from PyQt5.QtWidgets import (QApplication, QDialog,QGridLayout,
        QLineEdit, QListWidget,QListWidgetItem, QWidget,QMenu)
from PyQt5.QtGui import QIcon,QColor,QPainter,QFontMetricsF,QDrag,QCursor

class DropLineEdit(QLineEdit):

 def __init__(self, parent=None):
  super(DropLineEdit, self).__init__(parent)
  self.setAcceptDrops(True)


 def dragEnterEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.accept()
  else:
   event.ignore()


 def dragMoveEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.setDropAction(Qt.CopyAction)
   event.accept()
  else:
   event.ignore()


 def dropEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   data = event.mimeData().data("application/x-icon-and-text")
   stream = QDataStream(data, QIODevice.ReadOnly)
   text = ""
   text=stream.readQString()
   self.setText(text)
   event.setDropAction(Qt.CopyAction)
   event.accept()
  else:
   event.ignore()


class DnDMenuListWidget(QListWidget):

 def __init__(self, parent=None):
  super(DnDMenuListWidget, self).__init__(parent)
  self.setAcceptDrops(True)
  self.setDragEnabled(True)
  self.dropAction = Qt.CopyAction


 def dragEnterEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.accept()
  else:
   event.ignore()


 def dragMoveEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.setDropAction(Qt.MoveAction)
   event.accept()
  else:
   event.ignore()


 def dropEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   data = event.mimeData().data("application/x-icon-and-text")
   stream = QDataStream(data, QIODevice.ReadOnly)
   text = ""
   icon = QIcon()
   text=stream.readQString()
   stream>>icon
   menu = QMenu(self)
   menu.addAction("&Copy", self.setCopyAction)
   menu.addAction("&Move", self.setMoveAction)
   if menu.exec_(QCursor.pos()):
    item = QListWidgetItem(text, self)
    item.setIcon(icon)
    event.setDropAction(self.dropAction)
    event.accept()
    return
   else:
    event.setDropAction(Qt.IgnoreAction)
  event.ignore()


 def setCopyAction(self):
  self.dropAction = Qt.CopyAction


 def setMoveAction(self):
  self.dropAction = Qt.MoveAction


 def startDrag(self, dropActions):
  item = self.currentItem()
  icon = item.icon()
  data = QByteArray()
  stream = QDataStream(data, QIODevice.WriteOnly)
  stream.writeQString(item.text())
  stream<<icon
  mimeData = QMimeData()
  mimeData.setData("application/x-icon-and-text", data)
  drag = QDrag(self)
  drag.setMimeData(mimeData)
  pixmap = icon.pixmap(24, 24)
  drag.setHotSpot(QPoint(12, 12))
  drag.setPixmap(pixmap)
  if (drag.exec(Qt.MoveAction|Qt.CopyAction) == Qt.MoveAction):
   self.takeItem(self.row(item))


class DnDCtrlListWidget(QListWidget):

 def __init__(self, parent=None):
  super(DnDCtrlListWidget, self).__init__(parent)
  self.setAcceptDrops(True)
  self.setDragEnabled(True)


 def dragEnterEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.accept()
  else:
   event.ignore()


 def dragMoveEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   action = Qt.MoveAction
   if event.keyboardModifiers() & Qt.ControlModifier:
    action = Qt.CopyAction
   event.setDropAction(action)
   event.accept()
  else:
   event.ignore()


 def dropEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   data = event.mimeData().data("application/x-icon-and-text")
   stream = QDataStream(data, QIODevice.ReadOnly)
   text = ""
   icon = QIcon()
   text=stream.readQString()
   stream>>icon
   item = QListWidgetItem(text, self)
   item.setIcon(icon)
   action = Qt.MoveAction
   if event.keyboardModifiers() & Qt.ControlModifier:
    action = Qt.CopyAction
   event.setDropAction(action)
   event.accept()
  else:
   event.ignore()


 def startDrag(self, dropActions):
  item = self.currentItem()
  icon = item.icon()
  data = QByteArray()
  stream = QDataStream(data, QIODevice.WriteOnly)
  stream.writeQString(item.text())
  stream<<icon
  mimeData = QMimeData()
  mimeData.setData("application/x-icon-and-text", data)
  drag = QDrag(self)
  drag.setMimeData(mimeData)
  pixmap = icon.pixmap(24, 24)
  drag.setHotSpot(QPoint(12, 12))
  drag.setPixmap(pixmap)
  if (drag.exec(Qt.MoveAction|Qt.CopyAction) == Qt.MoveAction):
   self.takeItem(self.row(item))


class DnDWidget(QWidget):

 def __init__(self, text, icon=QIcon(), parent=None):
  super(DnDWidget, self).__init__(parent)
  self.setAcceptDrops(True)
  self.text = text
  self.icon = icon


 def minimumSizeHint(self):
  fm = QFontMetricsF(self.font())
  if self.icon.isNull():
   return QSize(fm.width(self.text), fm.height() * 1.5)
  return QSize(34 + fm.width(self.text), max(34, fm.height() * 1.5))


 def paintEvent(self, event):
  height = QFontMetricsF(self.font()).height()
  painter = QPainter(self)
  painter.setRenderHint(QPainter.Antialiasing)
  painter.setRenderHint(QPainter.TextAntialiasing)
  painter.fillRect(self.rect(), QColor(Qt.yellow).lighter())
  if self.icon.isNull():
   painter.drawText(10, height, self.text)
  else:
   pixmap = self.icon.pixmap(24, 24)
   painter.drawPixmap(0, 5, pixmap)
   painter.drawText(34, height,
        self.text + " (Drag to or from me!)")


 def dragEnterEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.accept()
  else:
   event.ignore()


 def dragMoveEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   event.setDropAction(Qt.CopyAction)
   event.accept()
  else:
   event.ignore()


 def dropEvent(self, event):
  if event.mimeData().hasFormat("application/x-icon-and-text"):
   data = event.mimeData().data("application/x-icon-and-text")
   stream = QDataStream(data, QIODevice.ReadOnly)
   self.text = ""
   self.icon = QIcon()
   self.text=stream.readQString()
   stream>>self.icon

   event.setDropAction(Qt.CopyAction)
   event.accept()
   self.updateGeometry()
   self.update()
  else:
   event.ignore()


 def mouseMoveEvent(self, event):
  self.startDrag()
  QWidget.mouseMoveEvent(self, event)


 def startDrag(self):
  icon = self.icon
  if icon.isNull():
   return
  data = QByteArray()
  stream = QDataStream(data, QIODevice.WriteOnly)
  stream.writeQString(self.text)
  stream<<icon
  mimeData = QMimeData()
  mimeData.setData("application/x-icon-and-text", data)
  drag = QDrag(self)
  drag.setMimeData(mimeData)
  pixmap = icon.pixmap(24, 24)
  drag.setHotSpot(QPoint(12, 12))
  drag.setPixmap(pixmap)
  drag.exec(Qt.CopyAction)


class Form(QDialog):

 def __init__(self, parent=None):
  super(Form, self).__init__(parent)

  dndListWidget = DnDMenuListWidget()
  path = os.path.dirname(__file__)
  for image in sorted(os.listdir(os.path.join(path, "images"))):
   if image.endswith(".png"):
    item = QListWidgetItem(image.split(".")[0].capitalize())
    item.setIcon(QIcon(os.path.join(path,
         "images/{0}".format(image))))
    dndListWidget.addItem(item)
  dndIconListWidget = DnDCtrlListWidget()
  dndIconListWidget.setViewMode(QListWidget.IconMode)
  dndWidget = DnDWidget("Drag to me!")
  dropLineEdit = DropLineEdit()

  layout = QGridLayout()
  layout.addWidget(dndListWidget, 0, 0)
  layout.addWidget(dndIconListWidget, 0, 1)
  layout.addWidget(dndWidget, 1, 0)
  layout.addWidget(dropLineEdit, 1, 1)
  self.setLayout(layout)

  self.setWindowTitle("Custom Drag and Drop")

if __name__ == "__main__":
 app = QApplication(sys.argv)
 form = Form()
 form.show()
 app.exec_()

运行结果:

python3+PyQt5重新实现自定义数据拖放处理

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
初学python数组的处理代码
Jan 04 Python
Python3连接MySQL(pymysql)模拟转账实现代码
May 24 Python
Python的requests网络编程包使用教程
Jul 11 Python
Python排序搜索基本算法之插入排序实例分析
Dec 11 Python
快速了解Python开发中的cookie及简单代码示例
Jan 17 Python
详谈Pandas中iloc和loc以及ix的区别
Jun 08 Python
Python实现的括号匹配判断功能示例
Aug 25 Python
Python实现繁体中文与简体中文相互转换的方法示例
Dec 18 Python
Python 共享变量加锁、释放详解
Aug 28 Python
Django restframework 框架认证、权限、限流用法示例
Dec 21 Python
Python3-异步进程回调函数(callback())介绍
May 02 Python
Python爬虫headers处理及网络超时问题解决方案
Jun 19 Python
python之从文件读取数据到list的实例讲解
Apr 19 #Python
python实现读取大文件并逐行写入另外一个文件
Apr 19 #Python
python按行读取文件,去掉每行的换行符\n的实例
Apr 19 #Python
PyQt5每天必学之拖放事件
Aug 27 #Python
sublime python3 输入换行不结束的方法
Apr 19 #Python
PyQt5每天必学之像素图控件QPixmap
Apr 19 #Python
PyQt5每天必学之单行文本框
Apr 19 #Python
You might like
帅气的琦玉老师
2020/03/02 日漫
php中inlcude()性能对比详解
2012/09/16 PHP
php判断手机浏览还是web浏览,并执行相应的动作简单实例
2016/07/28 PHP
javascript自定义startWith()和endWith()的两种方法
2013/11/11 Javascript
jQuery jcrop插件截图使用方法
2013/11/20 Javascript
node.js实现多图片上传实例
2014/06/03 Javascript
浅谈Jquery核心函数
2015/06/18 Javascript
详解JavaScript ES6中的模板字符串
2015/07/28 Javascript
jQuery实现的简单折叠菜单(折叠面板)效果代码
2015/09/16 Javascript
js倒计时抢购实例
2015/12/20 Javascript
this,this,再次讨论javascript中的this,超全面(经典)
2016/01/05 Javascript
JavaScript下的时间格式处理函数Date.prototype.format
2016/01/27 Javascript
JS文件/图片从电脑里面拖拽到浏览器上传文件/图片
2017/03/08 Javascript
bootstrap 设置checkbox部分选中效果
2017/04/20 Javascript
AngularJS  ng-repeat遍历输出的用法
2017/06/19 Javascript
Angularjs实现下拉框联动的示例代码
2017/08/22 Javascript
JavaScript常用数组操作方法,包含ES6方法
2020/05/10 Javascript
BootStrap表单验证中的非Submit类型按钮点击时触发验证的坑
2019/09/05 Javascript
浅析vue-router中params和query的区别
2019/12/24 Javascript
JavaScript布尔运算符原理使用解析
2020/05/06 Javascript
在vue中封装方法以及多处引用该方法详解
2020/08/14 Javascript
如何通过Proxy实现JSBridge模块化封装
2020/10/22 Javascript
[19:14]DOTA2 HEROS教学视频教你分分钟做大人-维萨吉
2014/06/24 DOTA
python之文件的读写和文件目录以及文件夹的操作实现代码
2016/08/28 Python
浅谈Python爬取网页的编码处理
2016/11/04 Python
pandas DataFrame实现几列数据合并成为新的一列方法
2018/06/08 Python
Django+uni-app实现数据通信中的请求跨域的示例代码
2019/10/12 Python
DC Shoes荷兰官方网站:美国极限运动品牌
2019/10/22 全球购物
房地产资料员岗位职责
2014/07/02 职场文书
迎国庆横幅标语
2014/10/08 职场文书
南极大冒险观后感
2015/06/05 职场文书
幼儿园见习总结
2015/06/23 职场文书
2015年小学总务工作总结
2015/07/21 职场文书
【海涛DOTA】D-cup邀请赛NV.cn vs DT.Love
2022/04/01 DOTA
vue如何实现关闭对话框后刷新列表
2022/04/08 Vue.js
mysql序号rownum行号实现方式
2022/12/24 MySQL