# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import (QPushButton, QWidget,
QLineEdit, QApplication)
#为了重新实现某些方法,所以要定义一个Button类,继承QPushButton
class Button(QPushButton):
def __init__(self ,title,parent ):
super().__init__(title,parent)
self.setAcceptDrops(True) #使该控件接受drop(放下)事件。
#重新实现dragEnterEvent()方法,并设置可接受的数据类型(在这里是普通文本)。
def dragEnterEvent(self,e):
if e.mimeData().hasFormat('text/plain'):
e.accept()
else:
e.ignore()
#dropEvent(self , e) 定义了在drop事件发生时的行为
def dropEvent(self , e):
self.setText(e.mimeData().text())
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
edit = QLineEdit('' ,self)
edit.setDragEnabled(True) #允许拖拽
edit.move(30,35)
but = Button("Button" ,self)
but.move(190,65)
self.setWindowTitle("Simple drag & drop")
self.setGeometry(300,300,300,150)
#self.show()
if __name__ == "__main__":
app=QApplication(sys.argv)
ex = Example()
ex.show()
app.exec_()
谢谢支持,打赏二维码: