QTimer';s连接到超时方法在TestCases(Python)中不起作用

QTimer';s连接到超时方法在TestCases(Python)中不起作用,python,qt,timer,pyqt,testcase,Python,Qt,Timer,Pyqt,Testcase,我刚刚完成了一个软件,现在想借助python的TestCase对它进行测试。方法test\u show\u video应启动QTimer。它连接到test\u run\u iteration,它每0,1秒将一个索引相加一次。在调用assert之前,该方法有三秒的时间对索引求和,因此它应该大于零。但事实并非如此。有人有线索吗?事实上,与计时器的超时连接似乎是错误的 try: app = QtGui.QApplication(sys.argv) except RuntimeError:

我刚刚完成了一个软件,现在想借助python的
TestCase
对它进行测试。方法
test\u show\u video
应启动
QTimer
。它连接到
test\u run\u iteration
,它每0,1秒将一个索引相加一次。在调用
assert
之前,该方法有三秒的时间对索引求和,因此它应该大于零。但事实并非如此。有人有线索吗?事实上,与计时器的超时连接似乎是错误的

try:
    app = QtGui.QApplication(sys.argv)
except RuntimeError:
    app = QtCore.QCoreApplication.instance()

class TestProgressPresenter(TestCase):

    def test_show_video(self):

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.test_run_iteration)
        self.timer.start(100)
        self.index = 0

        millis = start_time = int(round(time.time() * 1000))

        while start_time + 3000 > millis:
            millis = int(round(time.time() * 1000))

        assert self.index > 0

    def test_run_iteration(self):
        self.index += 1

在这里,您将在
while
循环期间阻塞Qt事件循环3秒钟。实际上,在控件返回到事件循环之前,计时器的
超时信号不会被调用,而此时while完成并且
test\u show\u video
完成

如果要触发计时器,应确保在while循环检查期间处理事件。为此,您可以使用以下内容:

while start_time + 3000 > millis:
    millis = int(round(time.time() * 1000))
    QApplication.processEvents(QEventLoop.AllEvents)
使用本地事件循环可以更轻松地等待几秒钟:

self.loop = QtCore.QEventLoop()
QTimer.singleShot(3000, loop.quit)
loop.exec()

assert self.index > 0