【发布时间】:2017-12-05 07:01:16
【问题描述】:
我想用 pyqt5 的 Drag&Drop 方法获取和显示图像。例如,像这张图片,
我想制作拖放空间和图像显示空间。
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”。所以当我拖放图片时,没有任何反应。
【问题讨论】:
-
你从哪里得到图像?
-
你确定格式是
image/*? -
感谢 cmets。我通过拖放从桌面获取图像,但无法获取。我试图将“image/*”改成“.jpg”,但没有任何反应。我该如何纠正?
-
执行下一次更改:
def dragEnterEvent(self, e): print(e.mimeData().formats()) -
打印下一句。因为太长,我分开。
标签: python python-3.x pyqt pyqt5