Reputation: 53
Lately I wrote this program where I have a QMainWindow with a push button and also a QDialog which opens up as push button is pressed. I also have a [text] (It's written above infoWindow class) and I want that to appear on QDialog word by word, but now It appears all together as my program finishes working. I've searched a lot but couldn't find what I was exactly searching for.So if you could tell me some ways of making my [text] appear word by word that would be amazing:)))
Here's my code
import time , sys
from PyQt5 import QtWidgets
from PyQt5 import uic
from PyQt5.QtWidgets import QTextBrowser
text = ["Lorem ", "Ipsum", " is ", "simply", " dummy", " text", " of the printing", " and", " typesetting", " industry"]
class infoWindow(QtWidgets.QDialog):
def __init__(self):
super(infoWindow, self).__init__()
uic.loadUi(r"window_design\info_window.ui", self)
self.setFixedSize(850, 500)
def textAdd(self):
self.show()
for word in text:
self.infoList.addItem(word)
time.sleep(0.2)
class main(QtWidgets.QMainWindow):
def __init__(self):
super(main, self).__init__()
uic.loadUi(r"window_design\main.ui", self)
self.info_window = infoWindow()
self.setFixedSize(850, 500)
self.pushButton.clicked.connect(self.info_window.textAdd)
if __name__ == '__main__':
my_app = QtWidgets.QApplication(sys.argv)
window = main()
window.show()
sys.exit(my_app.exec())
Upvotes: 0
Views: 147
Reputation: 48231
GUI systems are event driven, meaning that control must always return to the application main thread as soon as possible in order to allow proper UI updates and user interaction. Using blocking functions, like for loops and sleep
, will prevent all that, so the result is that the interface is only updated as soon as the function returns: not only you'll have to wait until all sleeps have expired, but you'll also see only the final result (all items shown all at once).
The solution is to use QTimer, which ensures that control is properly returned to the application and functions are executed when required without blocking anything.
In this case, you can copy the list and just pop elements from it at regular intervals until the list is empty:
class infoWindow(QtWidgets.QDialog):
def __init__(self):
super(infoWindow, self).__init__()
uic.loadUi(r"window_design\info_window.ui", self)
self.setFixedSize(850, 500)
self.wordList = text[:]
def textAdd(self):
self.show()
self.nextWord()
def nextWord(self):
if not self.wordList:
return
self.infoList.addItem(self.wordList.pop(0))
QtCore.QTimer.singleShot(200, self.nextWord)
Upvotes: 2