spootnx spootnx - 7 months ago 46
Python Question

How to update QProgressBar from another process or thread

Pushing the button starts 100 rounds cycle. Using

QLabel.setText()
method we update
self.label
widget straight from running
clicked()
function.

Aside from updating
self.label
we would like to update the
progessbar
widget as well.
But since
progessbar
is a local variable we can't update it from inside of
onClick()
function.

How should I arrange the code or what could be done to make sure the
progressbar
widget is easy to reach for an update?

enter image description here

import time

class ProgressBar(QtGui.QProgressBar):
def __init__(self, parent=None, total=20):
super(ProgressBar, self).__init__(parent=parent)

self.setMinimum(1)
self.setMaximum(105)
self.setTextVisible(True)

def set_to_value(self, value):
self.setValue(value)
QtGui.qApp.processEvents()

def closeEvent(self, event):
self._active=False


class Dialog(QtGui.QDialog):
def __init__(self):
super(QtGui.QDialog,self).__init__()

layout = QtGui.QVBoxLayout()
self.setLayout(layout)
self.label = QtGui.QLabel('idle...')
layout.addWidget(self.label)

progressbar = ProgressBar(self)
layout.addWidget(progressbar)

button = QtGui.QPushButton('Process')
button.clicked.connect(self.onClick)
layout.addWidget(button)

def onClick(self):
for i in range(101):
message = '...processing %s of 100'%i
self.label.setText(message)
QtGui.qApp.processEvents()
time.sleep(1)


if __name__ == '__main__':
app = QtGui.QApplication([])
dialog = Dialog()
dialog.resize(300, 100)
dialog.show()
app.exec_()

Answer

Declare the progress bar as:

self.progressbar = ProgressBar(self)