如何仅在python中使用pyqt5按住按钮时运行我的函数

如何仅在python中使用pyqt5按住按钮时运行我的函数,python,pyqt5,Python,Pyqt5,我怎样才能制作一个只在按住按钮(比如说一秒钟)并在释放时停止的按钮来执行其下的代码 from PyQt5.QtWidgets import QApplication, QWidget, QPushButton from PyQt5.QtGui import QIcon from PyQt5.QtCore import pyqtSlot class App(QWidget): def __init__(self): super().__init__()

我怎样才能制作一个只在按住按钮(比如说一秒钟)并在释放时停止的按钮来执行其下的代码

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot


class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 button '
        self.left = 500
        self.top = 200
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('PyQt5 button', self)
        button.setToolTip('This is an example button')
        button.move(100, 70)
        button.clicked.connect(self.on_click)

        self.show()

    @pyqtSlot()
    def on_click(self):
        print('PyQt5 button click')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_()) ```

您没有提到在按下按钮时要执行什么样的函数,但是假设您想在按下按钮时每隔一秒左右执行一个函数

在这种情况下,您可以使用
QTimer
并将要执行的函数连接到
QTimer.timeout
信号

然后,您可以使用
按钮。按下
按钮。释放
信号以启动和停止计时器

例如:

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QProgressBar
from PyQt5.QtCore import QTimer


class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 button '
        self.left = 500
        self.top = 200
        self.width = 320
        self.height = 200
        self.initUI()

        self.counter = 0
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.on_timeout)

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        vlayout = QVBoxLayout(self)

        button = QPushButton('PyQt5 button', self)
        button.setToolTip('This is an example button')

        # connect slots
        button.pressed.connect(self.on_press)
        button.released.connect(self.on_release)

        self.progress = QProgressBar(self)
        self.progress.setValue(0)

        vlayout.addWidget(button)
        vlayout.addWidget(self.progress)

        self.show()

    # function that should be run periodically while button is pressed
    def on_timeout(self):
        self.counter += 1
        self.progress.setValue(self.counter)

    def on_press(self):
        self.progress.setValue(0)
        self.counter = 0
        self.timer.start(100)

    def on_release(self):
        self.timer.stop()


if __name__ == '__main__':
    app = QApplication([])
    ex = App()
    app.exec()