python - 定时器无法连接到pyqt5中的插槽

标签 python pyqt pyqt5

我无法将计时器连接到 move() 插槽 timer.timeout.connect(self.move) 这不起作用 但是QtCore.QTimer.singleShot(50, self.move)这只是一步,而不是更多。

class Bullet(QGraphicsRectItem):
    def __init__(self):
        super().__init__()

        self.setRect(0,0,10,50)

        #timer = QTimer()
        #timer.timeout.connect( self.move)
        #timer.start(50)
        QtCore.QTimer.singleShot(50, self.move)

    def move(self):
        print("Timer Clicked")
        self.setPos(self.x(), self.y()-10)

最佳答案

问题很简单,函数中创建的变量是局部变量,当函数完成时将被消除,因此信号不会触发,而是 QTimer.singleShot() 有一个全局变量范围,解决方案是扩展计时器的范围,为此您必须使其成为该类的成员。

class Bullet(QGraphicsRectItem):
    def __init__(self):
        super().__init__()

        self.setRect(0,0,10,50)

        self.timer = QTimer()
        self.timer.timeout.connect(self.move)
        self.timer.start(50)

    def move(self):
        print("Timer Clicked")
        self.setPos(self.x(), self.y()-10)

关于python - 定时器无法连接到pyqt5中的插槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51442487/

相关文章:

python - 使用 Emacs Jedi(在 Anaconda 中)时可以避免使用 virtualenv 吗?

python - 为什么这个递归函数超过了python中的最大长度?

python - 更改 qtablewidget 中的颜色(单击)

python - 在 QGraphicsView 中播放图像序列(神秘的内存泄漏)

Python生成器代替类对象作为强化学习环境

javascript - PyQt - QObject 未定义

python - 如何拥有多个工具栏

python - 如何重启 PyQt5 应用程序

python - 在 QtDesigner GUI 中嵌入 matplotlib 图

python - 静态链接 Python,但仍支持外部 .pyd 模块