Pyside2 (Qt For Python) progress bar function implementation

Pyside2 (Qt For Python) progress bar function implementation

Progress bar (QProgressBar)

Today we will introduce the use of PySide2 progress bar ( QProgressBar ), as shown below:
Insert image description here

illustrate

The progress bar is also a commonly used control. When the program needs to do a time-consuming task (such as statistics, downloading files, etc.), it can be used to indicate the progress of the operation to the user . And with the progress display, the user knows that the application is still running and there is no problem.

The QProgressBar progress bar calls each progress a step.

setRangeWe can set the number of steps through its method, such as

progressBar.setRange(0,10)

The above code divides the progress into 5 steps. Then, use setValuethe method to specify which step is currently completed, for example:

progressBar.setValue(7)

It means that 7/10 is completed, which is 70%, and the progress bar will show 70% progress.

Progress bar program sample code
import time
from PySide2.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QProgressBar
from PySide2.QtCore import QThread, Signal

class Worker(QThread):
    progress = Signal(int)

    def run(self):
        for i in range(101):
            time.sleep(0.1)  # 模拟耗时操作
            self.progress.emit(i)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("进度条")
        self.setGeometry(100, 100, 300, 150)

        self.central_widget = QWidget(self)
        self.setCentralWidget(self.central_widget)

        self.layout = QVBoxLayout()
        self.central_widget.setLayout(self.layout)

        self.progress_bar = QProgressBar(self)
        self.layout.addWidget(self.progress_bar)

        self.button = QPushButton("开始", self)
        self.button.clicked.connect(self.start_process)
        self.layout.addWidget(self.button)

    def start_process(self):
        self.worker = Worker()
        self.worker.progress.connect(self.update_progress)
        self.worker.start()

    def update_progress(self, value):
        self.progress_bar.setValue(value)

if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()
  • Minimum and maximum steps can be specified using setMinimum() and setMaximum() ; the default values ​​are 0 and 99.

    • The current step is set by **setValue()**
    • The progress bar can be restarted through the reset() method
  • If both the minimum and maximum values ​​are set to 0, i.e. setRange(0, 0), then the bar will display a busy indicator instead of the percentage of steps, as shown below:

    img

Progress bar advanced example

Usually, when we use a progress bar, it is usually bound to the specific task progress. There are two common situations:

  • Bind with data. For example, if the object of the operation is a large amount of data, you can set the range of the progress bar to the total amount of data. The progress bar will be updated every time the corresponding amount of data is run.

    • The following is a code example for binding data volume and progress bar
    total_rows = len(list(sheet1.iter_rows()))  # 获取总行数
    current_row = 0 # 设置当前运行行数
    
    current_row += 1 # 每运行一行,变量自动+1
    progress = int(current_row / total_rows * 100)
    compareWin.update_progress_bar(100)  # 更新进度条
    
  • Bind to the same thread. If the current project runs in multiple threads, you can bind the progress bar to the thread to facilitate real-time reflection of the program running status. The following is a code example for binding the thread to the progress bar.

    import sys
    from PySide2.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QProgressBar
    from PySide2.QtCore import QThread, Signal
    
    class WorkerThread(QThread):
      # 定义一个信号,用于更新进度条
      update_progress = Signal(int)
    
      def run(self):
        for i in range(101):
          # 发送信号,更新进度条
          self.update_progress.emit(i)
          self.msleep(50)  # 模拟耗时操作
    
    class MainWindow(QWidget):
      def __init__(self):
        super().__init__()
    
        self.initUI()
    
      def initUI(self):
        self.setWindowTitle('进度条和线程绑定示例')
        self.setGeometry(100, 100, 400, 200)
    
        # 创建垂直布局
        layout = QVBoxLayout(self)
    
        # 创建进度条
        self.progress_bar = QProgressBar(self)
        layout.addWidget(self.progress_bar)
    
        # 创建按钮,点击按钮启动线程
        self.start_button = QPushButton('开始', self)
        self.start_button.clicked.connect(self.startThread)
        layout.addWidget(self.start_button)
    
        self.setLayout(layout)
    
      def startThread(self):
        # 创建线程实例
        self.thread = WorkerThread()
    
        # 将线程的信号连接到更新进度条的槽函数
        self.thread.update_progress.connect(self.updateProgressBar)
    
        # 启动线程
        self.thread.start()
    
        # 禁用按钮,防止多次点击
        self.start_button.setEnabled(False)
    
      def updateProgressBar(self, value):
        # 更新进度条的值
        self.progress_bar.setValue(value)
    
        # 如果进度达到100%,启用按钮
        if value == 100:
          self.start_button.setEnabled(True)
    
    if __name__ == "__main__":
      app = QApplication(sys.argv)
      window = MainWindow()
      window.show()
      sys.exit(app.exec_())
    
    

Guess you like

Origin blog.csdn.net/H931053/article/details/134806770