Hi,
I’m trying to create a simple class recitation app where it randomly picks from the list of students.
It works, but I want it to change in real time, so there’s a bit of suspense who is being picked.
You can see in the illustration video below that the console updates the names in real time but the QtWidget does not:
Here is the working code so far:
import sys
import os
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QApplication, QMainWindow, QSpinBox, QWidget, QPushButton, QTextEdit, QVBoxLayout, QHBoxLayout, QLineEdit, QLabel
from PySide2.QtGui import QPixmap
from time import sleep, perf_counter
import time
import random
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Class Recitation")
# Widget
root_img_path = 'img'
self.image_list = []
for root, dirs, files in os.walk(root_img_path):
for f in files:
img_path = os.path.join(root_img_path, f)
first_name = f.split('_')[0]
last_name = f.split('_')[1]
self.image_list.append( (img_path, first_name + " " + last_name ) )
# creating label
self.label = QLabel(self)
# loading image
#self.pixmap = QPixmap('img/Eijirou_Kirishima_Portrait.png')
self.pixmap = QPixmap(self.image_list[0][0])
# adding image to label
self.label.setPixmap(self.pixmap)
self.name_label = QLabel()
self.name_label.setText(self.image_list[0][1])
self.pick_btn = QPushButton("Pick")
self.pick_btn.setObjectName("Pick")
self.pick_btn.clicked.connect(self.random_pick)
# Layout Creations
hbox = QHBoxLayout()
# hbox.addWidget(self.search_button)
# hbox.addWidget(self.search_bar)
vbox = QVBoxLayout()
vbox.addWidget(self.label)
vbox.addWidget(self.name_label)
vbox.addWidget(self.pick_btn)
# vbox.addWidget(self.result_text_edit)
layout = QVBoxLayout()
layout.addLayout(hbox)
layout.addLayout(vbox)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
def random_pick(self):
choice_list = self.image_list
time_started = time.perf_counter()
counter = 0
for x in range(0,10000):
random_pick = random.choice(choice_list)
self.name_label.setText(random_pick[1])
self.label.setPixmap(random_pick[0])
print (random_pick[1])
sleep(counter)
current_time = time.perf_counter()
time_elapse = current_time - time_started
counter += 0.0001 * (2**4)
if time_elapse >= 5:
break
return random_pick
def change_name(self):
self.name_label.setText("Name Changed")
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
Is there a way around this?
Thanks