【发布时间】:2020-03-25 18:15:44
【问题描述】:
我有这个关于如何拖动和移动 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