我想使用 pyqt5 的拖放方法获取和显示图像。例如,像这张图片,
我想制作拖放空间和图像显示空间。
import sys
from PyQt5.QtWidgets import (QPushButton, QWidget,
QLineEdit, QApplication)
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Button(QPushButton):
def __init__(self, title, parent):
super().__init__(title, parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, e):
if e.mimeData().hasFormat('image/*'):
e.accept()
else:
e.ignore()
def dropEvent(self, e):
self.label.setPixmap(QPixmap(event.mimeData().imageData()))
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
button = Button("",self)
button.resize(100,100)
button.setIcon(QIcon("gazo1.jpg"))
button.setIconSize(QSize(100,100))
button.move(0, 0)
self.label = QLabel(self)
self.label.setPixmap(QPixmap('gazo2.jpg'))
self.label.move(150,150)
self.setWindowTitle('Simple drag & drop')
self.setGeometry(300, 300, 300, 300)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
app.exec_()
我希望如果我将 jpg-image 拖放到左上角,图像将显示在中间空间。 但是当我将jpg图像拖到左上角空间时,不显示“drop enabled mark”。所以当我拖放图片时,没有任何反应。
请您参考如下方法:
当你想从桌面拖拽一个图像时,这个图像的路径通过本地 url 提供,以验证它使用 mimeData()。 hasUrls(),和urls()获取url,然后我们用toLocalFile()方法获取本地路径,以上都是在以下代码中实现:
class Button(QPushButton):
def __init__(self, title, parent):
super().__init__(title, parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, e):
m = e.mimeData()
if m.hasUrls():
e.accept()
else:
e.ignore()
def dropEvent(self, e):
m = e.mimeData()
if m.hasUrls():
self.parent().label.setPixmap(QPixmap(m.urls()[0].toLocalFile()))
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
button = Button("",self)
button.resize(100,100)
button.setIcon(QIcon("gazo1.jpg"))
button.setIconSize(QSize(100,100))
button.move(0, 0)
self.label = QLabel(self)
self.label.setPixmap(QPixmap('gazo2.png'))
self.label.move(150,150)
self.setWindowTitle('Simple drag & drop')
self.setGeometry(300, 300, 300, 300)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
app.exec_()
