Pyqt5可拖动QPushButton

问题描述 投票:0回答:1

我有关于如何拖动和移动QPushButton的示例代码。该代码的唯一问题是,拖动并释放按钮时,按钮状态保持选中状态。

有人可以帮我更改代码,以便在拖动按钮并释放后自动取消选中状态。因此,我不必单击即可取消选中它。

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import Qt

class DragButton(QPushButton):

    def mousePressEvent(self, event):
        self.__mousePressPos = None
        self.__mouseMovePos = None
        if event.button() == Qt.LeftButton:
            self.__mousePressPos = event.globalPos()
            self.__mouseMovePos = event.globalPos()

        super(DragButton, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            # adjust offset from clicked point to origin of widget
            currPos = self.mapToGlobal(self.pos())
            globalPos = event.globalPos()
            diff = globalPos - self.__mouseMovePos
            newPos = self.mapFromGlobal(currPos + diff)
            self.move(newPos)

            self.__mouseMovePos = globalPos

        super(DragButton, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if self.__mousePressPos is not None:
            moved = event.globalPos() - self.__mousePressPos 
            if moved.manhattanLength() > 3:
                event.ignore()
                return

        super(DragButton, self).mouseReleaseEvent(event)

def clicked():
    print ("click as normal!")

if __name__ == "__main__":
    app = QApplication([])
    w   = QWidget()
    w.resize(800,600)

    button = DragButton("Drag", w)
    button.clicked.connect(clicked)

    w.show()
    app.exec_() 
python pyqt5 qwidget qpushbutton
1个回答
0
投票

您在mouseReleaseEvent中的return,这意味着您没有让按钮知道它实际上已经释放了鼠标,从而使状态保持为按下状态。

def mouseReleaseEvent(self, event):
    if self.__mousePressPos is not None:
        moved = event.globalPos() - self.__mousePressPos 
        if moved.manhattanLength() > 3:
            event.ignore()
            return # <-- the problem is here!

    super(DragButton, self).mouseReleaseEvent(event)

[如果将鼠标移动几像素(在曼哈顿长度以下),您会看到它的行为正确,因此,如果需要,您必须完全删除该if块,或者在返回之前调用self.setDown(False)以避免发送clicked信号。

© www.soinside.com 2019 - 2024. All rights reserved.