QTimer 在对话框关闭后运行

use*_*754 1 python qt pyqt4

我有一个QDialog,在其中创建一个QTimer Object ,它每n秒触发一个函数。关闭对话框(点击 x 按钮)后,计时器仍在触发并且似乎没有被破坏。我怎样才能阻止它?目前作为解决方法,我在输入 closeEvent()时显式调用Qtimer.stop()

我希望当窗口关闭时,每个类成员都会被删除,即使我显式调用解构函数,Qtimer 对象仍然存在。

from PyQt4 import QtGui, QtCore
import sys



def update():
    print "tick..."

class Main(QtGui.QDialog):

    def __init__(self, parent = None):
        super(Main, self).__init__(parent)


        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(update)
        self.timer.start(2000)

        # scroll area
        self.scrollArea = QtGui.QScrollArea()
        self.scrollArea.setWidgetResizable(True)

        # main layout
        self.mainLayout = QtGui.QVBoxLayout()


        self.setLayout(self.mainLayout)


    def closeEvent(self, evt):
        print "class event called"
        self.timer.stop()

myWidget = Main()
myWidget.show()
Run Code Online (Sandbox Code Playgroud)

phy*_*att 6

http://doc.qt.io/qt-5/timers.html

定时器功能的主要 API 是QTimer. 该类提供常规定时器,当定时器触发时发出信号,并进行继承,QObject以便它很好地适合大多数 GUI 程序的所有权结构。正常的使用方法是这样的:

QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateCaption()));
timer->start(1000);
Run Code Online (Sandbox Code Playgroud)

QTimer对象被制作为该小部件的子级,以便当删除该小部件时,计时器也会被删除。接下来,它的timeout() 信号连接到将完成工作的插槽,它以 1000 毫秒的值开始,表示每秒都会超时。

在 C++ 中,计时器的父级是 widget 或其他QObject,然后它们的生命周期与 的生命周期相关联QObject,但在不需要计时器时停止计时器仍然是一个很好的做法。当您调用 时,布局将获得父级setLayout。计时器不知道其父级,因此当小部件被销毁时它不会被销毁。它只是位于堆上,仍然由QApplication事件循环运行。

http://doc.qt.io/qt-5/qobject.html#setParent

因此,要么将 self 传递给 的构造函数QTimer,要么调用setParentQTimer将其正确设置到对象树中。

http://doc.qt.io/qt-5/objecttrees.html

更新:显然setParent在 PyQt 中不起作用。self只需在构造函数中传入即可QTimer

希望有帮助。