PyQt5 用按键同步按钮按下释放动画,解决长按时按钮自动重复动作

功能需求:

准备通过写一个上位机遥控器界面控制电机转动,具体功能与赛车游戏类似,当按下键盘一个键位时(以数字4键为例),界面上的“上”按钮变暗,只触发按钮事件一次,直到松开键盘键位,按钮复原,电机停转。

ps:起初想以按钮的setAutoRepeat()函数实现,发现没有效果,qt小白,有知道的大佬可以指教一下。

代码只给出类里面具体的两个重载函数,其余部分不懂的可以评论区:

def keyPressEvent(self,event):         #重载
    if event.key() == Qt.Key_4:
        print("按键被按下")
        self.pushButton.click()        #点击创建的按钮实例,前提:按钮已绑定自定义事件
        self.pushButton.setEnabled(False)  #阻止按钮事件发生,防止重复触发按钮事件

def keyReleaseEvent(self, event):      #重载
    if event.key() == Qt.Key_4:     
        if event.isAutoRepeat():       #按钮按下状态,为True
            pass
        else:                          #按钮释放状态,为False
            print("键盘被松开")        
            self.pushButton.setEnabled(True)  #按钮释放,恢复点击按钮触发事件功能
            self.pushButton.toggle()          #按钮释放,恢复按钮状态(按钮由暗变亮)

具体实现效果简单描述就是,长按按键4时,只会传输一次控制指令给电机,界面的对应按钮会从亮变暗(自己设置的效果,亮代表没按,暗代表按钮按下),只有释放按钮时会传输一次停止控制指令给电机,界面的对应按钮会从暗变亮。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用QTransform来实现按钮的旋转动画。具体步骤如下: 1. 导入必要的模块 ```python from PyQt5.QtCore import QPropertyAnimation, QTransform, QRect from PyQt5.QtWidgets import QPushButton ``` 2. 创建QPushButton对象并设置初始状态 ```python button = QPushButton('Rotate') button.setGeometry(QRect(50, 50, 100, 50)) button.show() ``` 3. 创建QTransform对象并设置初始状态 ```python transform = QTransform() transform.rotate(0) # 初始状态为0度旋转 ``` 4. 创建QPropertyAnimation对象并设置属性 ```python animation = QPropertyAnimation(button, b"transform") animation.setDuration(1000) # 动画持续时间为1秒 animation.setStartValue(transform) # 设置起始状态 ``` 5. 在槽函数中更新QTransform对象并启动动画 ```python def rotate_button(): global transform transform.rotate(90) # 每次旋转90度 animation.setEndValue(transform) # 设置终止状态 animation.start() button.clicked.connect(rotate_button) ``` 完整代码如下: ```python from PyQt5.QtCore import QPropertyAnimation, QTransform, QRect from PyQt5.QtWidgets import QPushButton button = QPushButton('Rotate') button.setGeometry(QRect(50, 50, 100, 50)) button.show() transform = QTransform() transform.rotate(0) animation = QPropertyAnimation(button, b"transform") animation.setDuration(1000) animation.setStartValue(transform) def rotate_button(): global transform transform.rotate(90) animation.setEndValue(transform) animation.start() button.clicked.connect(rotate_button) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值