I am trying to messing up with something and I am not able to create a widget using threading. Could someone take a look at my test script and let me know why this does not work?
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import *
import threading
import time
class Main(QMainWindow):
def __init__(self):
super(Main, self).__init__()
self._build_ui()
main_thread = threading.Thread(target=self.thread_function)
main_thread.start()
def thread_function(self):
i = 0
while True:
message = "Message number: {}".format(i)
print (message)
self.create_message_widget(message)
i+=1
time.sleep(1)
def create_message_widget(self, message):
print ("Testing 3")
self.label = QLabel(self)
self.label.setText(message)
self.verticalLayout.addWidget(self.label)
def _build_ui(self):
self.setWindowTitle("Testing Window")
# set the central widget and main layout
self.centralWidget = QWidget(self)
self.verticalLayout = QVBoxLayout(self)
self.setCentralWidget(self.centralWidget)
self.centralWidget.setLayout(self.verticalLayout)
self.button = QPushButton("Run")
self.button.clicked.connect(lambda: self.create_message_widget("Testing 1"))
# adding widgets to the window
self.verticalLayout.addWidget(self.button)
self.create_message_widget("Testing 2")
self.create_message_widget("Testing 2")
self.create_message_widget("Testing 2")
# show main window
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Main()
sys.exit(app.exec())
The following script shows 3 functions where I did few Testing X
.
You can notice the Testing 2
are created fine.
When we click the button we can see Testing 1
which is populated by button press.
In thread_function
I call create_message_widget
function and I thought that should automatically create widget every 1 sec but it does not do anything. Could someone explain why and if this is possible to make it works?