Home > Net >  How to figure out whether button is continuosly pressed or not in PyQt5?
How to figure out whether button is continuosly pressed or not in PyQt5?

Time:03-04

For my application, I need my lift system to go up as long as the button is pressed and it should stop when I don't press the button.

clicked() function is not functional for this purpose. However pressed() and released() functions also didn't work.

I snipped related section of my code below. My aim is to print "Pressed" text as long as button is pressed

def __init__(self):
    manual_button = QPushButton('Lift Button')
    manual_button.pressed.connect(press_function)
    self.manual_grid.addWidget(manual_button, 0, 1)

def press_function(self):
    print('pressed')

Thanks

CodePudding user response:

Just use the pressed and released signals to start/stop a QTimer. Something like...

#!/usr/local/bin/python3
import os
import sys
from PyQt5.QtCore import(QTimer)
from PyQt5.QtWidgets import(QApplication, QPushButton)

def button_pressed(timer):
    timer.start(100)

def button_released(timer):
    timer.stop()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    pb = QPushButton("Press")
    timer = QTimer()
    pb.pressed.connect(lambda checked = False: button_pressed(timer))
    pb.released.connect(lambda checked = False: button_released(timer))
    timer.timeout.connect(lambda: print('Button Pressed'))
    pb.show()
    app.exec_()
  • Related