凌的博客

您现在的位置是: 首页 > 学无止境 > python > 

python

PyQt5 拖动事件 实例

2019-08-26 python 1395

1.png

import sys
from PyQt5.QtWidgets import QWidget,QApplication,QTextEdit,QVBoxLayout,QLabel
from PyQt5.QtGui import QDragEnterEvent,QPixmap
import os

class Drop(QWidget):

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

    def initUI(self):
        self.setAcceptDrops(True)
        h = QVBoxLayout()

        self.txt = QTextEdit()
        self.txt.setAcceptDrops(False)
        self.lbl = QLabel("some thing")
        h.addWidget(self.txt,5)
        h.addWidget(self.lbl,5)

        self.setLayout(h)

        self.setGeometry(300,300,300,300)
        self.setWindowTitle("拖动事件")

    def dragEnterEvent(self,e: QDragEnterEvent):

        if e.mimeData().hasUrls():
            for url in e.mimeData().urls():
                self.txt.setPlainText(url.path()+"\n")

            filename = e.mimeData().urls()[0].path()
            basename,ext = os.path.splitext(os.path.basename(filename))
            print(basename)
            if ext.upper() == ".PNG":
                e.acceptProposedAction()
            else:
                e.ignore()

    def dropEvent(self, e):
        filename = e.mimeData().urls()[0].path()
        realpath = filename[1:len(filename)]
        print(realpath)
        self.lbl.setPixmap(QPixmap(realpath))
        e.accept()

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


文章评论

0条评论