I want the calculation process in my python program to display the QProgressBar. Wrote a class:

class ProgressBar(QWidget): def __init__(self): super().__init__() self.pbar = QProgressBar(self) self.init_ui() def init_ui(self): self.pbar.setGeometry(30, 40, 200, 25) self.pbar.setValue(0) self.setGeometry(400, 300, 280, 170) self.setWindowTitle('Updating...') self.show() def loading(self, percentage): self.pbar.setValue(percentage) 

The instance is created in another class, and the current number of percents was supposed to be passed through the loading function. The simplest example:

 pb = ProgressBar() for i in range(100): pb.loading(i) time.sleep(1) 

As a result, the ProgressBar is created, but displayed as an empty widget until 100% comes, then it closes.

Apparently, somewhere you need to specify the correct signal, tried several options to set the slot and the signal through valueChanged () did not work. Tell me how to fix it?

Marked as a duplicate by the participants Sergey Gornostaev , 0xdb , LFC , aleksandr barakin , iluxa1810 on 12 March at 11:43 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Show how you "pass the current percent through the loading function". - Sergey Gornostaev
  • Added to question - TheSaGe
  • four
  • one
    I don’t know how it will be in python, but in C ++ you need to let the message loop work, i.e. call QCoreApplication :: processEvents to display the changes - Pavel Gridin
  • one
    in your opinion you probably need to call QApplication.processEvents() in a loop, after pb.loading(i) - Pavel Gridin

1 answer 1

Heavy tasks usually work in separate threads. From which data is periodically transmitted to the graphical interface, including for display, for example, in the progress bar. But since it is not clear what you are doing, there is no minimum example, I will give an example of a demonstration of the ProgressBar using QTimer.

 import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * class Widget(QWidget): def __init__(self): super().__init__() self.pbar = QProgressBar(self) self.percentage = 0 self.pbar.setTextVisible(self.percentage) self.pbar.setValue(self.percentage) button = QPushButton("Старт ProgressBar") button.clicked.connect(self.onClicked) self.gridLayout = QGridLayout(self) self.gridLayout.addWidget(self.pbar) self.gridLayout.addWidget(button) def onClicked(self): self.timer = QTimer(self) self.timer.timeout.connect(self.ProgressBar) self.timer.start(500) def ProgressBar(self): self.pbar.setValue(self.percentage) self.pbar.setTextVisible(self.percentage) if self.percentage >= 100: self.timer.stop() self.percentage = 0 else: self.percentage += 5 if __name__ == '__main__': import sys app = QApplication(sys.argv) w = Widget() w.setGeometry(400, 300, 300, 150) w.setWindowTitle('Demo ProgressBar') w.show() sys.exit(app.exec()) 

enter image description here