拖放事件与拖放操作

链接:https://pan.baidu.com/s/1kyC3FJxlOBBn2hXKceHSRw 
提取码:9q4n

import sys,os
from PyQt5.QtWidgets import QApplication,QWidget
from PyQt5.QtGui import QPixmap
from ui_widget import Ui_Widget
from PyQt5 import QtCore

class QmyWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui=Ui_Widget()
        self.ui.setupUi(self)
        self.setAcceptDrops(True)
        self.ui.plainTextEdit.setAcceptDrops(False)#不允许放置
        self.ui.LabPic.setAcceptDrops(False)#由父窗体处理
        # self.ui.LabPic.setScaledContents(True)
    
    ##================事件处理函数==================================
    def dragEnterEvent(self, event):
        self.ui.plainTextEdit.clear()
        self.ui.plainTextEdit.appendPlainText("dragEnterEvent事件mimeData().formats()")
        for strLine in event.mimeData().formats():#格式数据
            self.ui.plainTextEdit.appendPlainText(strLine)
        self.ui.plainTextEdit.appendPlainText("\ndragEnterEvent事件mimeData().urls()")
        for url in event.mimeData().urls():
            self.ui.plainTextEdit.appendPlainText(url.path())
        if(event.mimeData().hasUrls()):
            filename=event.mimeData().urls()[0].fileName()#只有文件名
            basename,ext=os.path.splitext(filename)#文件名和后缀
            ext=ext.upper()
            if(ext==".JPG"):#只接受jpg文件
                event.acceptProposedAction()#接受拖放操作
            else:
                event.ignore()
        else:
            event.ignore()
    def dropEvent(self, event):
        filename=event.mimeData().urls()[0].path()#完整文件名
        cnt=len(filename)
        realname=filename[1:cnt]#去掉最左边的"/"
        pixmap=QPixmap(realname)
        self.ui.LabPic.setPixmap(pixmap)
        event.accept()

if __name__=="__main__":
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)#自适应缩放
    app=QApplication(sys.argv)
    form=QmyWidget()
    form.show()
    sys.exit(app.exec_())

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/108143627