当计时器

时间:2015-05-18 15:50:43

标签: python qt pyside

我需要定期发出信号。定时器执行某些功能,发出我想要的信号。由于某种原因,没有发出此功能。我能够在最小代码上重现错误(参见下文)。如果我在没有计时器的情况下做同样的事情一切正常:

from threading import Timer
import time
from PySide import QtCore

class testSignals(QtCore.QObject):
    signal = QtCore.Signal();
    def __init__(self):
        QtCore.QObject.__init__(self)

    def run(self):
        self.signal.emit()

class testConnection():
    @QtCore.Slot()
    def receiveMe(self):
        print('Signal received')

    # signal is emmited when data is changed
    def __init__(self):
        test = testSignals()
        test.signal.connect(self.receiveMe)
        test.run();

test = testConnection()

我能够在以下代码中重现我的问题:

from threading import Timer
import time
from PySide import QtCore

class testSignals(QtCore.QObject):

    signal = QtCore.Signal();

    def __init__(self):
        self.is_running = False
        QtCore.QObject.__init__(self)
        self.start()

    def emitMe(self):
        self.is_running = False
        self.start()
        # print("emitMe")
        self.signal.emit()

    def start(self):
        if not self.is_running:
            self._timer = Timer(0.2, self.emitMe)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False

class testConnection():
    @QtCore.Slot()
    def receiveMe(self):
        print('Signal received')

    # signal is emmited when data is changed
    def __init__(self):
        test = testSignals()
        test.signal.connect(self.receiveMe)
        test.start();
        time.sleep(2.0)
        test.stop();

test = testConnection()

短语“已接收信号”未在屏幕上打印。

1 个答案:

答案 0 :(得分:2)

正如@ekhumoro在评论中所说,QTimer帮助了很多。我需要一个事件循环。我发布代码以使答案有效。我用QTimer重写了它,这使得一切都变得更加简单。请注意,我需要调用QCoreApplication来运行线程。同样,这只是重现我需要做的最小代码。

import time
from PySide import QtCore
from probeConnection import ProbeConnection 

class testSignals(QtCore.QObject):

    def __init__(self):
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.tick)
        self.start()

    def tick(self):
        print("tick")

    def getData(self):
        return time.strftime('%H:%M:%S')

    def start(self):
        self.timer.start(1000)

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

class testConnection():
    def receiveMe(self):
        print('time: ' + self.test.getData())

    def __init__(self):
        self.test = testSignals()
        self.test.timer.timeout.connect(self.receiveMe)


app = QtCore.QCoreApplication([])
test = testConnection()
timer = QtCore.QTimer()
timer.singleShot(4000,app.exit)
app.exec_()

它产生:

tick
time: 13:23:37
tick
time: 13:23:38
tick
time: 13:23:39
tick
time: 13:23:40