PySide Qt:拖放图像

时间:2016-11-19 14:31:09

标签: python qt drag-and-drop pyside

标题基本上都说明了一切。我想创建一个可以在窗口内拖动的图像。到目前为止我的代码完成了所有这些,但由于某种原因,图像看起来很小,即使我使用scaled()函数来调整它。此外,如果我更改scaled()函数内的值,图像将消失。

from PySide.QtGui import *
from PySide.QtCore import *
import sys


class Label(QLabel):
    def __init__(self, title, parent):
        super(Label, self).__init__(title, parent)
        self.setup()

    def setup(self):
        folder_pic = QPixmap("path")
        folder_size = folder_pic.scaled(64, 64)
        self.label = QLabel(self)
        self.label.setPixmap(folder_size)

    def mouseMoveEvent(self, e):

        if e.buttons() != Qt.LeftButton:
            return

        mimeData = QMimeData(self)

        drag = QDrag(self)
        drag.setMimeData(mimeData)
        drag.setHotSpot(e.pos() - self.rect().topLeft())

        dropAction = drag.start(Qt.MoveAction)

class Example(QWidget):

    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        self.setAcceptDrops(True)
        self.button = Label("", self)
        self.button.move(100, 65)
        self.setWindowTitle('Click or Move')
        self.setGeometry(300, 300, 280, 150)


    def dragEnterEvent(self, e):

        e.accept()

    def dropEvent(self, e):

        position = e.pos()
        self.button.move(position)
        e.setDropAction(Qt.MoveAction)
        e.accept()



if __name__ == "__main__":
    app = QApplication(sys.argv)
    mywin = Example()
    mywin.show()
    sys.exit(app.exec_())

我的代码基于本教程http://zetcode.com/gui/pysidetutorial/dragdrop/

1 个答案:

答案 0 :(得分:2)

在拖动对象上设置像素图:

drag.setPixmap(self.pixmap())

但要实现这一点,您还需要这个修复:

def setup(self):
    folder_pic = QPixmap("path")
    folder_size = folder_pic.scaled(64, 64)
    self.setPixmap(folder_size)