# -*- coding: utf-8 -*-
from PySide2 import QtCore
from PySide2 import QtWidgets
import sys
class DoublePushButton(QtWidgets.QPushButton):
def __init__(self, msec=300, *args, **kwargs):
super(DoublePushButton, self).__init__(*args, **kwargs)
self.button = None
self.clickedTimer = QtCore.QTimer() # 创建计时器
self.clickedTimer.setInterval(msec) # 延迟时间
self.clickedTimer.timeout.connect(self.mouseClick) # 连接到单点函数
def mouseClick(self):
"""单击函数"""
if self.isDown(): # 按下状态返回
return
self.clickedTimer.stop() # 停止计时器
# ↓执行
if self.button == QtCore.Qt.LeftButton:
print("1左")
elif self.button == QtCore.Qt.MidButton:
print("1中")
elif self.button == QtCore.Qt.RightButton:
print("1右")
def mouseDoubleClick(self):
"""双击函数"""
if self.button == QtCore.Qt.LeftButton:
print("2左")
elif self.button == QtCore.Qt.MidButton:
print("2中")
elif self.button == QtCore.Qt.RightButton:
print("2右")
def mousePressEvent(self, event): # 复写一下事件,不然它只会反应左键点击
if self.hitButton(event.pos()):
self.setDown(True)
self.repaint()
event.accept()
else:
event.ignore()
def mouseReleaseEvent(self, event):
"""鼠标松开事件"""
if not self.isDown(): # 鼠标按下时会执行setDown,这里判断按钮状态是否抬起
event.ignore() # 没有按下则忽略
return
self.setDown(False) # 按下则抬起
self.button = event.button() # 记录按下的按键
if self.hitButton(event.pos()): # 在按钮内
if self.clickedTimer.isActive(): # 计时器是否开启
self.clickedTimer.stop() # 结束计时器
self.mouseDoubleClick() # 执行双击命令
else:
self.clickedTimer.start() # 开启计时器
event.accept() # 继续
else:
if self.clickedTimer.isActive():
self.clickedTimer.stop()
event.ignore() # 不在按钮内则忽略
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
win = DoublePushButton()
win.show()
sys.exit(app.exec_())
评论