晚上。我在理解QTimer及其工作方式以及使下面的代码正常工作方面都遇到了一些困难。尽管我讨厌复制/粘贴,但我还是无法弄清楚。目的是将程序运行15秒钟,然后完全退出。其他所有内容都可以正常工作,但是当我尝试集成QTimer来计算经过了多少秒时,无论我尝试哪种变化,它都无能为力或者只是根本不起作用。下面是最新的代码:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QMovie
from PyQt5.QtCore import QTimer
import winsound
import time
import sys
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(321, 249)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(0, 0, 320, 248))
self.label.setFrameShape(QtWidgets.QFrame.Box)
self.label.setOpenExternalLinks(False)
self.label.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
#Plays the movie in the Label
movie = QMovie("giphy.gif")
self.label.setMovie(movie)
movie.start()
#Plays the sound with the movie
winsound.PlaySound("magicwrd.wav", winsound.SND_ASYNC|winsound.SND_LOOP)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
#Borrowed and modified from here: https://stackoverflow.com/questions/46656634/pyqt5-qtimer-count-until-specific-seconds
#Goal is to run the application for 15 seconds and then exit out completely.
def start_timer(self, slot, count=1, interval=1000):
counter = 0
def handler():
nonlocal counter
counter += 1
slot(counter)
if counter >= count:
timer.stop()
timer.deleteLater()
timer = QtCore.QTimer()
timer.timeout.connect(handler)
timer.start(interval)
def timer_func(self, count):
if count >= 5:
sys.exit(app.exec_())
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
Ui_MainWindow.start_timer(Ui_MainWindow.timer_func, 5)
app.exec_()
晚上。我在理解QTimer及其工作方式以及使下面的代码正常工作方面都遇到了一些困难。尽管我讨厌复制/粘贴,但我还是无法弄清楚。 ...
如果要在T秒内完成应用程序,则必须使用QTimer::singleShot()
,以便在触发该应用程序时调用QCoreApplication::quit()
: