Progress bar python pyqt5

pyqt5
Введение в бары прогресса

Progress Bars являются неотъемлемой частью пользовательского интерфейса и помогают пользователям получить представление о времени, оставшемся для данного процесса, который выполняется в графическом интерфейсе. В этом разделе будут рассмотрены основы реализации индикатора выполнения в вашем собственном приложении.

В этом разделе будет легко коснуться QThread и нового механизма сигналов / слотов. Некоторые читатели видят также видение виджетов PyQt5.

При добавлении примеров используйте только встроенные модули PyQt5 и Python для демонстрации функциональности.

Только PyQt5

замечания

Экспериментировать с этими примерами — лучший способ начать обучение.

Базовая панель управления PyQt

Это очень простой индикатор прогресса, который использует только то, что необходимо на минимальном минимуме.

Было бы разумно прочитать весь этот пример до конца.

import sys import time from PyQt5.QtWidgets import (QApplication, QDialog, QProgressBar, QPushButton) TIME_LIMIT = 100 class Actions(QDialog): """ Simple dialog that consists of a Progress Bar and a Button. Clicking on the button results in the start of a timer and updates the progress bar. """ def __init__(self): super().__init__() self.initUI() def initUI(self): self.setWindowTitle('Progress Bar') self.progress = QProgressBar(self) self.progress.setGeometry(0, 0, 300, 25) self.progress.setMaximum(100) self.button = QPushButton('Start', self) self.button.move(0, 30) self.show() self.button.clicked.connect(self.onButtonClick) def onButtonClick(self): count = 0 while count < TIME_LIMIT: count += 1 time.sleep(1) self.progress.setValue(count) if __name__ == "__main__": app = QApplication(sys.argv) window = Actions() sys.exit(app.exec_()) 

Панель выполнения сначала импортируется так, как from PyQt5.QtWidgets import QProgressBar

Затем он инициализируется, как и любой другой виджет в QtWidgets

Метод line self.progress.setGeometry(0, 0, 300, 25) определяет положения x,y в диалоговом окне, ширину и высоту индикатора выполнения.

Затем мы перемещаем кнопку с помощью .move() на 30px вниз, чтобы между двумя виджетами был пробел в 5 5px .

Здесь self.progress.setValue(count) используется для обновления прогресса. Установка максимального значения с использованием .setMaximum() также автоматически рассчитает значения для вас. Например, если максимальное значение установлено TIME_LIMIT 50, тогда как TIME_LIMIT равно 100, он будет TIME_LIMIT от 0 до 2 до 4 процентов вместо 0 к 1 к 2 в секунду. Вы также можете установить минимальное значение, используя .setMinimum() заставляя индикатор выполнения начинаться с заданного значения.

Выполнение этой программы приведет к созданию графического интерфейса, подобного этому.

Диалог «Прогресс-бар» не отвечает

Как вы можете видеть, графический интерфейс будет определенно зависеть и не реагировать, пока счетчик не встретит условие TIME_LIMIT . Это связано с тем, что time.sleep заставляет ОС полагать, что программа застряла в бесконечном цикле.

Итак, как мы преодолеем эту проблему? Мы можем использовать класс потоков, который предоставляет PyQt5.

import sys import time from PyQt5.QtCore import QThread, pyqtSignal from PyQt5.QtWidgets import (QApplication, QDialog, QProgressBar, QPushButton) TIME_LIMIT = 100 class External(QThread): """ Runs a counter thread. """ countChanged = pyqtSignal(int) def run(self): count = 0 while count < TIME_LIMIT: count +=1 time.sleep(1) self.countChanged.emit(count) class Actions(QDialog): """ Simple dialog that consists of a Progress Bar and a Button. Clicking on the button results in the start of a timer and updates the progress bar. """ def __init__(self): super().__init__() self.initUI() def initUI(self): self.setWindowTitle('Progress Bar') self.progress = QProgressBar(self) self.progress.setGeometry(0, 0, 300, 25) self.progress.setMaximum(100) self.button = QPushButton('Start', self) self.button.move(0, 30) self.show() self.button.clicked.connect(self.onButtonClick) def onButtonClick(self): self.calc = External() self.calc.countChanged.connect(self.onCountChanged) self.calc.start() def onCountChanged(self, value): self.progress.setValue(value) if __name__ == "__main__": app = QApplication(sys.argv) window = Actions() sys.exit(app.exec_()) 

Давайте разложим эти изменения.

from PyQt5.QtCore import QThread, pyqtSignal 

Эта строка импортирует Qthread которая представляет собой реализацию PyQt5 для разделения и запуска некоторых частей (например, функций, классов) программы в фоновом режиме (также известна как многопоточность). Эти части также называются нитями. Все программы PyQt5 по умолчанию имеют основной поток, а другие (рабочие потоки) используются для выгрузки дополнительных трудоемких и трудоемких задач в фоновом режиме, сохраняя при этом основную программу.

Второй импорт pyqtSignal используется для отправки данных (сигналов) между рабочим и основным потоками. В этом случае мы будем использовать его, чтобы сообщить основному потоку обновить индикатор выполнения.

Теперь мы переместили цикл while для счетчика в отдельный класс External .

class External(QThread): """ Runs a counter thread. """ countChanged = pyqtSignal(int) def run(self): count = 0 while count < TIME_LIMIT: count +=1 time.sleep(1) self.countChanged.emit(count) 

QThread мы по существу преобразуем External в класс, который можно запускать в отдельном потоке. Темы могут также запускаться или останавливаться в любое время, добавляя к ним преимущества.

Здесь countChanged - текущий прогресс, а pyqtSignal(int) сообщает рабочему потоку, что передаваемый сигнал имеет тип int . Хотя self.countChanged.emit(count) просто посылает сигнал на любые соединения в основном потоке (обычно он может использоваться для связи с другими рабочими потоками).

def onButtonClick(self): self.calc = External() self.calc.countChanged.connect(self.onCountChanged) self.calc.start() def onCountChanged(self, value): self.progress.setValue(value) 

Когда нажимается self.onButtonClick , запускается self.onButtonClick , а также запускает поток. Нить начинается с .start() . Следует также отметить, что мы подключили сигнал self.calc.countChanged мы создали ранее, к методу, используемому для обновления значения индикатора выполнения. При каждом обновлении параметра External::run::count значение int также отправляется в onCountChanged .

Именно так GUI мог бы следить за внесением этих изменений.

Панель выполнения QThread

Он также должен чувствовать себя намного более отзывчивым и не замерзнет.

Источник

QProgressBar¶

Inheritance diagram of PySide2.QtWidgets.QProgressBar

../../_images/windows-progressbar.png

A progress bar is used to give the user an indication of the progress of an operation and to reassure them that the application is still running.

The progress bar uses the concept of steps . You set it up by specifying the minimum and maximum possible step values, and it will display the percentage of steps that have been completed when you later give it the current step value. The percentage is calculated by dividing the progress ( value() - minimum() ) divided by maximum() - minimum() .

You can specify the minimum and maximum number of steps with setMinimum() and setMaximum . The current number of steps is set with setValue() . The progress bar can be rewound to the beginning with reset() .

If minimum and maximum both are set to 0, the bar shows a busy indicator instead of a percentage of steps. This is useful, for example, when using QNetworkAccessManager to download items when they are unable to determine the size of the item being downloaded.

Constructs a progress bar with the given parent .

By default, the minimum step value is set to 0, and the maximum to 100.

Specifies the reading direction of the text for vertical progress bars.

The text is rotated 90 degrees clockwise.

The text is rotated 90 degrees counter-clockwise.

Note that whether or not the text is drawn is dependent on the style. Currently CleanLooks and Plastique draw the text. Mac, Windows and WindowsVista style do not.

This property holds the alignment of the progress bar.

PySide2.QtWidgets.QProgressBar. format ( ) ¶ Return type :

This property holds the string used to generate the current text.

%p - is replaced by the percentage completed. %v - is replaced by the current value. %m - is replaced by the total number of steps.

Initialize option with the values from this QProgressBar . This method is useful for subclasses when they need a QStyleOptionProgressBar , but don’t want to fill in all the information themselves.

This property holds whether or not a progress bar shows its progress inverted.

If this property is true , the progress bar grows in the other direction (e.g. from right to left). By default, the progress bar is not inverted.

This property holds whether the current completed percentage should be displayed.

This property may be ignored by the style (e.g., QMacStyle never draws the text).

This property holds the progress bar’s maximum value.

When setting this property, the minimum is adjusted if necessary to ensure that the range remains valid. If the current value falls outside the new range, the progress bar is reset with reset() .

PySide2.QtWidgets.QProgressBar. minimum ( ) ¶ Return type :

This property holds the progress bar’s minimum value.

When setting this property, the maximum is adjusted if necessary to ensure that the range remains valid. If the current value falls outside the new range, the progress bar is reset with reset() .

PySide2.QtWidgets.QProgressBar. orientation ( ) ¶ Return type :

This property holds the orientation of the progress bar.

The orientation must be Horizontal (the default) or Vertical .

Reset the progress bar. The progress bar “rewinds” and shows no progress.

This property holds the string used to generate the current text.

%p - is replaced by the percentage completed. %v - is replaced by the current value. %m - is replaced by the total number of steps.

alignment – Alignment

This property holds the alignment of the progress bar.

PySide2.QtWidgets.QProgressBar. setFormat ( format ) ¶ Parameters :

format – str

This property holds the string used to generate the current text.

%p - is replaced by the percentage completed. %v - is replaced by the current value. %m - is replaced by the total number of steps.

invert – bool

This property holds whether or not a progress bar shows its progress inverted.

If this property is true , the progress bar grows in the other direction (e.g. from right to left). By default, the progress bar is not inverted.

maximum – int

This property holds the progress bar’s maximum value.

When setting this property, the minimum is adjusted if necessary to ensure that the range remains valid. If the current value falls outside the new range, the progress bar is reset with reset() .

PySide2.QtWidgets.QProgressBar. setMinimum ( minimum ) ¶ Parameters :

minimum – int

This property holds the progress bar’s minimum value.

When setting this property, the maximum is adjusted if necessary to ensure that the range remains valid. If the current value falls outside the new range, the progress bar is reset with reset() .

PySide2.QtWidgets.QProgressBar. setOrientation ( arg__1 ) ¶ Parameters :

This property holds the orientation of the progress bar.

The orientation must be Horizontal (the default) or Vertical .

Sets the progress bar’s minimum and maximum values to minimum and maximum respectively.

If maximum is smaller than minimum , minimum becomes the only legal value.

If the current value falls outside the new range, the progress bar is reset with reset() .

The QProgressBar can be set to undetermined state by using (0, 0).

textDirection – Direction

This property holds the reading direction of the text for vertical progress bars.

This property has no impact on horizontal progress bars. By default, the reading direction is TopToBottom .

visible – bool

This property holds whether the current completed percentage should be displayed.

This property may be ignored by the style (e.g., QMacStyle never draws the text).

value – int

This property holds the progress bar’s current value.

Attempting to change the current value to one outside the minimum-maximum range has no effect on the current value.

PySide2.QtWidgets.QProgressBar. text ( ) ¶ Return type :

This property holds the descriptive text shown with the progress bar.

The text returned is the same as the text displayed in the center (or in some styles, to the left) of the progress bar.

The progress shown in the text may be smaller than the minimum value, indicating that the progress bar is in the “reset” state before any progress is set.

In the default implementation, the text either contains a percentage value that indicates the progress so far, or it is blank because the progress bar is in the reset state.

PySide2.QtWidgets.QProgressBar. textDirection ( ) ¶ Return type :

This property holds the reading direction of the text for vertical progress bars.

This property has no impact on horizontal progress bars. By default, the reading direction is TopToBottom .

This property holds the progress bar’s current value.

Attempting to change the current value to one outside the minimum-maximum range has no effect on the current value.

PySide2.QtWidgets.QProgressBar. valueChanged ( value ) ¶ Parameters :

value – int

© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Источник

Читайте также:  Html svg in div
Оцените статью