Hello World / plɹoM ollǝH

Programmers Live in Vain

PySide ドラッグ&ドロップ

忘れがちなポイント

  • setAcceptDrops(True)
  • 各イベントでevent.accept
  • ファイルパスはTextじゃなくてURL

f:id:dungeonneko:20170307160033g:plain

from PySide import QtCore, QtGui
import sys, os

class DragAndDrop(QtGui.QLabel):
    def __init__(self):
        super().__init__()
        self.setText('Drag and drop here')
        self.setAlignment(QtCore.Qt.AlignCenter)
        self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            event.ignore()

    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls():
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        filename = os.path.basename(event.mimeData().urls()[0].path())
        self.setText(filename)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    w = DragAndDrop()
    w.show()
    sys.exit(app.exec_())