PySide2文件拖入功能并添加遮罩
作者:YXN-python 阅读量:10 发布日期:2024-11-05
import sys
from PySide2.QtWidgets import QApplication, QMainWindow, QWidget, QLabel, QVBoxLayout
from PySide2.QtCore import Qt
from PySide2.QtGui import QDragEnterEvent, QDropEvent, QPalette, QColor
class Overlay(QWidget):
def __init__(self, parent=None):
super(Overlay, self).__init__(parent)
self.setAttribute(Qt.WA_TransparentForMouseEvents)
self.setAttribute(Qt.WA_NoSystemBackground)
# 设置邮件的布局和标签
layout = QVBoxLayout(self)
self.label = QLabel("释放以将文件放在此处", self)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet("color: #0196FF; font-size: 24px;")
layout.addWidget(self.label)
# 使背景半透明
self.setPalette(QPalette(QColor(0, 0, 0, 200)))
self.setAutoFillBackground(True)
self.hide() # 最初隐藏覆盖
def resizeEvent(self, event):
super().resizeEvent(event)
self.setGeometry(self.parent().rect())
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("松开鼠标以播放")
self.setAcceptDrops(True)
# 设置覆盖
self.overlay = Overlay(self)
self.overlay.setGeometry(self.rect())
def resizeEvent(self, event):
super().resizeEvent(event)
self.overlay.setGeometry(self.rect())
def dragEnterEvent(self, event: QDragEnterEvent):
if event.mimeData().hasUrls():
event.setDropAction(Qt.CopyAction)
event.accept()
self.overlay.show() # 拖动开始时显示覆盖
else:
event.ignore()
def dragLeaveEvent(self, event):
self.overlay.hide() # 拖动离开窗口时隐藏覆盖
event.accept()
def dropEvent(self, event: QDropEvent):
# 放下后隐藏覆盖
self.overlay.hide()
# 处理拖放的文件
urls = event.mimeData().urls()
for url in urls:
file_path = url.toLocalFile()
print("接收到文件:", file_path)
event.acceptProposedAction()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.resize(400, 300)
window.show()
sys.exit(app.exec_())
YXN-python
2024-11-05