背景:为了节约人力测试成本,模拟鼠标长按后松开,整理了这个简单的小demo
1、关键方法
实例鼠标按下事件
QMouseEvent(QEvent.MouseButtonPress, self.p_pos, Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton, Qt.NoModifier)
实例鼠标松开事件
QMouseEvent(QEvent.MouseButtonRelease, self.p_pos, Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton, Qt.NoModifier)
发送鼠标事件
QCoreApplication.sendEvent(self.tb, event)
2、测试代码
import os
import sys
from PyQt5.Qt import *
class Widget(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.resize(900, 600)
self.p_pos = QPoint(0, 0)
self.tb = QToolButton(self)
self.tb.move(100, 200)
self.tb.setAutoRepeat(True)
self.tb.setText("测试")
self.tb.clicked.connect(self.click_slot)
t = QTimer(self)
t.timeout.connect(self.timer_slot)
t.start(4000)
def timer_slot(self):
print("timer_slot触发")
self.custom_press()
def custom_press(self):
print("鼠标按下")
event = QMouseEvent(QEvent.MouseButtonPress, self.p_pos, Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton, Qt.NoModifier)
QCoreApplication.sendEvent(self.tb, event)
QTimer.singleShot(1000, self.custom_release)
def custom_release(self):
event = QMouseEvent(QEvent.MouseButtonRelease, self.p_pos, Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton, Qt.NoModifier)
QCoreApplication.sendEvent(self.tb, event)
print("鼠标松开")
def click_slot(self):
print("按钮被点击")
if __name__ == '__main__':
app = QApplication(sys.argv)
parent_dir_path, file_name = os.path.split(os.path.abspath(__file__))
_, parent_dir_name = os.path.split(parent_dir_path)
app.setApplicationDisplayName(f"[{parent_dir_name}][{file_name}]")
w = Widget()
w.show()
sys.exit(app.exec_())