How to create a loading warning for long processing thread on python?
I edit some code refer to the above website, in the following part there is new code:
import sys
import time
import _thread
from PyQt5.QtCore import QObject, pyqtSignal, Qt
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QInputDialog, QApplication, QProgressDialog
class Message(QObject):
finished = pyqtSignal()
def createAddress(password, name, obj):
print('Count in child thread. 0 sec')
time.sleep(1)
print('Count in child thread. 1 sec')
time.sleep(1)
print('Count in child thread. 2 sec')
time.sleep(1)
print('Count in child thread. 3 sec')
time.sleep(1)
print('Count in child thread. 4 sec')
time.sleep(1)
obj.finished.emit()
class Widget(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
lay = QVBoxLayout(self)
button = QPushButton("Start processing")
lay.addWidget(button)
button.clicked.connect(self.start_task)
self.message_obj = Message()
def start_task(self):
password = "password"
name, ok = QInputDialog.getText(None, 'Name the address', 'Enter the address name:')
if ok:
self.progress_indicator = QProgressDialog(self)
self.progress_indicator.setWindowModality(Qt.WindowModal)
self.progress_indicator.setRange(0, 0)
self.progress_indicator.setAttribute(Qt.WA_DeleteOnClose)
self.message_obj.finished.connect(self.progress_indicator.close, Qt.QueuedConnection)
self.progress_indicator.show()
_thread.start_new_thread(createAddress, (password, name, self.message_obj, ))
print('Count in main thread. 0 sec')
time.sleep(1)
print('Count in main thread. 1 sec')
time.sleep(1)
print('Count in main thread. 2 sec')
time.sleep(1)
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle("fusion")
w = Widget()
w.show()
sys.exit(app.exec_())
When the button clicked, CMD print the word in mainThread(start_task) and the word in subThread(createAddress) correctly. However, the progress bar is not shown until the mainThread complete to count.
How to make the progress bar show correctly while mainThread executing, Thanks.