在 PyQt5 中,要實(shí)現(xiàn) QPushButton 的拖放功能,你需要重新實(shí)現(xiàn)一些方法,如 mousePressEvent、mouseMoveEvent 和 dropEvent。以下是一個(gè)簡(jiǎn)單的例子:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtGui import QDrag
class DragButton(QPushButton):
def __init__(self, title, parent):
super().__init__(title, parent)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.dragStartPosition = event.pos()
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if not (event.buttons() & Qt.LeftButton):
return
if ((event.pos() - self.dragStartPosition).manhattanLength()
< QApplication.startDragDistance()):
return
drag = QDrag(self)
mimeData = QMimeData()
mimeData.setText(self.text())
drag.setMimeData(mimeData)
drag.exec_(Qt.MoveAction)
def dropEvent(self, event):
position = event.pos()
self.move(position)
event.accept()
class AppDemo(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setAcceptDrops(True)
self.button = DragButton('拖動(dòng)我', self)
self.button.move(100, 65)
self.setWindowTitle('QPushButton 拖放示例')
self.setGeometry(300, 300, 600, 400)
if __name__ == '__main__':
app = QApplication(sys.argv)
demo = AppDemo()
demo.show()
sys.exit(app.exec_())
這個(gè)例子中,我們創(chuàng)建了一個(gè)名為 DragButton 的自定義按鈕類,它繼承自 QPushButton。然后我們重寫了 mousePressEvent、mouseMoveEvent 和 dropEvent 方法,以實(shí)現(xiàn)拖放功能。
當(dāng)你運(yùn)行這個(gè)程序時(shí),你會(huì)看到一個(gè)包含一個(gè)可拖動(dòng)按鈕的窗口。你可以點(diǎn)擊并拖動(dòng)這個(gè)按鈕,將其移動(dòng)到窗口中的任意位置。