qt版本:pyside6
python测试版本:3.9.19
效果:
代码:
from PySide6.QtGui import QDragEnterEvent
from PySide6.QtWidgets import (QWidget, QApplication,
QHBoxLayout, QLabel,
QSizePolicy, QLayout)
class DragFileWidget(QWidget):
def __init__(self, parent=None, onFileDragIn=None):
super().__init__(parent)
if onFileDragIn is not None:
self.onFileDrag = onFileDragIn
self.setAcceptDrops(True)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
def setWidget(self, widget: QWidget):
base_layout = QHBoxLayout()
base_layout.setSizeConstraint(QLayout.SizeConstraint.SetMaximumSize)
base_layout.setContentsMargins(0, 0, 0, 0)
base_layout.addWidget(widget)
self.setLayout(base_layout)
def dragEnterEvent(self, event: QDragEnterEvent) -> None:
super(DragFileWidget, self).dragEnterEvent(event)
files = event.mimeData().urls()
if files:
event.accept()
else:
event.ignore()
def dropEvent(self, event: QDragEnterEvent):
super(DragFileWidget, self).dropEvent(event)
files = event.mimeData().urls()
for file in files:
file_path = file.toLocalFile()
if file_path:
self.onFileDragIn(file_path)
def onFileDragIn(self, path):
print(path)
if __name__ == '__main__':
app = QApplication([])
window = DragFileWidget()
label = QLabel()
label.setText("这里是文件上传区域")
window.setWidget(label)
label.setMinimumSize(50, 200)
label.setStyleSheet("background-color:white")
label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
window.show()
app.exec()
使用:功能性的部件
step 1:创建实例
widget = DragFileWidget(onFileDragIn=func)
step 2:创建回调函数
def func(path):
print(path)
step 3:填充内部的部件
label = QLabel()
label.setText("文件上传")
widget.setWidget(label)