1 回答

TA貢獻1860條經(jīng)驗 獲得超9個贊
你不需要子類化一個按鈕來移動它,如果你要在同一父級中移動對象,你當然不應該使用拖放。
此外,如果您要僅檢查按下右鍵時發(fā)生的移動,則應始終為其他情況調用基本實現(xiàn)(其他按鈕,或無按鈕,以防鼠標跟蹤
;按鈕通常不是這種情況,但這不是重點)。
在按鈕上安裝事件篩選器,并跟蹤以下事件:
QEvent.MouseButtonPress:如果按鈕是正確的,則為當前移動的小部件設置一個變量,并為當前鼠標位置設置另一個變量(假設,startPosition)
QEvent.MouseMove:如果當前移動小部件存在,請使用公式移動它
newPosition = currentPosition + eventPosition - startPosition
QEvent.MouseButtonRelease:清除當前移動的小部件
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.movingButton = None
def initUI(self):
self.button1 = QPushButton('Button1', self)
self.button1.setFixedSize(100,100)
# no need for this, every new widget is always placed at (0, 0)
# self.button1.move(0, 0)
self.button1.installEventFilter(self)
self.button2 = QPushButton('Button2', self)
self.button2.move(0, 110)
self.button2.installEventFilter(self)
self.setWindowTitle('Click or Move')
self.setGeometry(0, 0, 400, 400)
def eventFilter(self, source, event):
if source in (self.button1, self.button2):
if event.type() == QEvent.MouseButtonPress and event.button() == Qt.RightButton:
self.movingButton = source
self.startPos = event.pos()
# uncomment the following lines if you want to move the button while
# moving the mouse
# elif event.type() == QEvent.MouseMove and self.movingButton:
# self.movingButton.move(source.pos() + event.pos() - self.startPos)
elif event.type() == QEvent.MouseButtonRelease and self.movingButton:
self.movingButton.move(source.pos() + event.pos() - self.startPos)
self.movingButton = None
return super().eventFilter(source, event)
添加回答
舉報