將LineEdit的文本拖拽到下拉框中
""" 讓控件支持拖拽動作 A.setDragEnabled(True) 可以進行拖拽 B.setAcceptDrops(True) 可以接收拖拽 B需要兩個事件 1. dragEnterEvent 將A拖到B觸發 2. dropEvent 在B的區域放下A時觸發 """ import sys, math from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * class MyComboxBox(QComboBox): def __init__(self): super(MyComboxBox, self).__init__() self.setAcceptDrops(True) #構造A拖拽到B時的觸發 def dragEnterEvent(self, e): print(e) if e.mimeData().hasText(): e.accept() else: e.ignore() #構造將A放下以后B的操作 def dropEvent(self, e): self.addItem(e.mimeData().text()) #在下拉列表中添加文本 class DrapDropDemo(QWidget): def __init__(self): super(DrapDropDemo, self).__init__() formLayout = QFormLayout() formLayout.addRow(QLabel("請將左邊的文本拖拽到右邊的下拉列表中")) lineEdit = QLineEdit() lineEdit.setDragEnabled(True) #讓lineEdit可以拖動 combo = MyComboxBox() formLayout.addRow(lineEdit, combo) self.setLayout(formLayout) self.setWindowTitle("拖拽案例") if __name__ == "__main__": app = QApplication(sys.argv) main = DrapDropDemo() main.show() sys.exit(app.exec_())