这是一个仍然正确支持正常点击信号的可移动按钮的示例:
from PyQt4 import QtCore, QtGui
class DragButton(QtGui.QPushButton):
def mousePressEvent(self, event):
self.__mousePressPos = None
self.__mouseMovePos = None
if event.button() == QtCore.Qt.LeftButton:
self.__mousePressPos = event.globalPos()
self.__mouseMovePos = event.globalPos()
super(DragButton, self).mousePressEvent(event)
def mouseMoveEvent(self, event):
if event.buttons() == QtCore.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 = QtGui.QApplication([])
w = QtGui.QWidget()
w.resize(800,600)
button = DragButton("Drag", w)
button.clicked.connect(clicked)
w.show()
app.exec_()
在mousePressEvent
I 中,记录了初始起始位置和将在整个拖动过程中更新的位置。
在 中mouseMoveEvent
,我得到了小部件从单击位置到实际原点位置的适当偏移量,以便移动准确。
在 中mouseReleaseEvent
,我检查整体移动是否大于至少一个很小的量。如果是,那么它就是一个拖拽,我们忽略正常事件以不产生“点击”信号。否则,我们允许正常的事件处理程序产生点击。