I am trying to create a program, using PyQt, which currently consists of a stacked widget of 4 pages. A timer has been implemented, and after 3 seconds the page the user is currently on switches to the next page. I am currently trying to add a timer which shows the user how much time on that page they have left (ideally in seconds). However, I have no idea how to connect the timer to a counter, and have not been able to find anything which would be helpful.
Here is the current code, which is basically just the timer:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from StackedWidget import *
app = QApplication(sys.argv)
window = QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(window)
def NextTimer():
ui.stackedWidget.setCurrentIndex((ui.stackedWidget.currentIndex() + 1))
myTimer = QTimer()
myTimer.timeout.connect(NextTimer)
myTimer.start(3000)
I am trying to connect the timer to a counter of the class QLCDNumber,labelled Counter. At the current point there is no code which involves this counter, it just exists.
Thank you for any help.
Here is a working example in PyQt5 of how you can implement the functionality you described:
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
DURATION_INT = 3
class MyMainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.time_left_int = DURATION_INT
self.widget_counter_int = 0
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
vbox = QtWidgets.QVBoxLayout()
central_widget.setLayout(vbox)
self.pages_qsw = QtWidgets.QStackedWidget()
vbox.addWidget(self.pages_qsw)
self.time_passed_qll = QtWidgets.QLabel()
vbox.addWidget(self.time_passed_qll)
self.widget_one = QtWidgets.QLabel("This is widget one")
self.pages_qsw.addWidget(self.widget_one)
self.widget_two = QtWidgets.QLabel("This is widget two")
self.pages_qsw.addWidget(self.widget_two)
self.widget_three = QtWidgets.QLabel("This is widget three")
self.pages_qsw.addWidget(self.widget_three)
self.widget_four = QtWidgets.QLabel("This is widget four")
self.pages_qsw.addWidget(self.widget_four)
self.timer_start()
self.update_gui()
def timer_start(self):
self.time_left_int = DURATION_INT
self.my_qtimer = QtCore.QTimer(self)
self.my_qtimer.timeout.connect(self.timer_timeout)
self.my_qtimer.start(1000)
self.update_gui()
def timer_timeout(self):
self.time_left_int -= 1
if self.time_left_int == 0:
self.widget_counter_int = (self.widget_counter_int + 1) % 4
self.pages_qsw.setCurrentIndex(self.widget_counter_int)
self.time_left_int = DURATION_INT
self.update_gui()
def update_gui(self):
self.time_passed_qll.setText(str(self.time_left_int))
app = QtWidgets.QApplication(sys.argv)
main_window = MyMainWindow()
main_window.show()
sys.exit(app.exec_())
I hope this helps!