python 3+PyQt 5 사용자 정의 데이터 드래그 처리 다시 구현
18246 단어 python3PyQt5데이터 드래그 앤 드 롭
사용자 정의 데이터 MIME 데이터 형식 QMimeData,MIME 는 여러 구성 부분 을 가 진 사용자 정의 데 이 터 를 처리 하 는 표준화 형식 입 니 다.MIME 데 이 터 는 하나의 데이터 형식 과 하나의 키 형식 으로 C 를 구성 합 니 다.예 를 들 어 text/plain,text/html,image/png 은 사용자 정의 MIME 데 이 터 를 처리 하려 면 사용자 정의 데이터 형식 과 피 드 형식 을 선택 한 다음 에 데 이 터 를 QMimeData 대상 에 밀봉 해 야 합 니 다.이 예 에서 저 희 는 application/x-icon-and-text 형식의 새로운 MIME 데 이 터 를 만 듭 니 다.
주:
dragEnterEvent 이것 은 드래그 이벤트 의 함수 입 니 다.우 리 는 파일 을 프로그램 인터페이스 에 끌 어 들 여 열 어야 합 니 다.그 전에 setAcceptDrops(true)를 한 후에 끌 어야 합 니 다.그러나 acceptDrops 만 설정 하 는 것 이 부족 합 니 다.dragEnterEvent 이벤트 에서 끌 어 들 인 대상 을 선별 하여 mimedata 의 유형 이 당신 이 처리 할 수 있 는 지 판단 해 야 합 니 다.만약 에...이벤트.acceptProposed Action()을 호출 하여 실행 합 니 다.드래그 앤 드 롭 이벤트 가 끝나 면 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_()
실행 결과:두 번 째 부분:
#!/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_()
실행 결과:이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Jupyter 공식 DockerHub에 대한 메모에 기재되어 있다. base-notebook minimal-notebook scipy-notebook tensorflow-notebook datascience-notebook pyspark-notebook all-s...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.