- Виджеты в PyQt5
- QCheckBox (чекбокс)
- Кнопка переключателя (toogle button)
- QSlider (ползунок)
- QProgressBar (прогресс бар)
- QCalendarWidget (виджет календаря)
- Отслеживаем прогресс выполнения в Python
- Используем Progress
- Используем tqdm
- Используем alive-progress
- GUI индикатор прогресса для скрипта
- Индикатор в приложении PySimpleGUI
- Заключение
- Qt Documentation
- Table of Contents
- Previous topic
- Next topic
- Quick search
- QProgressBarВ¶
- SynopsisВ¶
- FunctionsВ¶
- Virtual functionsВ¶
- SlotsВ¶
- SignalsВ¶
- Detailed DescriptionВ¶
Виджеты в PyQt5
Виджеты – это основные строительные кирпичики приложения. PyQt5 имеет множество разнообразных виджетов, включая кнопки, чекбоксы, ползунки и списки. В этой части руководства, мы опишем несколько полезных виджетов: QCheckBox, ToggleButton, QSlider, QProgressBar и QCalendarWidget.
QCheckBox (чекбокс)
QCheckBox – чекбокс (виджет, который имеет два состояния: включен и выключен). Как правило, чекбоксы используют для функций приложения, которые могут быть включены или выключены.
В нашем примере, мы создаём чекбокс, который переключает заголовок окна.
Это конструктор QCheckBox.
Мы установили заголовок окна так, что мы должны к тому же проверять чекбокс. По умолчанию, заголовок окна не установлен и чекбокс выключен.
Мы связываем наш метод changeTitle(), с сигналом stateChanged. Метод changeTitle() будет переключать заголовок окна.
Если виджет помечен галочкой, мы устанавливаем заголовок окна. В противном случае, мы устанавливаем пустую строку в заголовке.
Кнопка переключателя (toogle button)
Кнопка переключателя – это QPushButton в особом режиме. Это кнопка, которая имеет два состояния: нажатое и не нажатое. Мы переключаемся между этими двумя состояниями, кликая по ней. Существуют ситуации, где эта функциональность отлично подходит.
В нашем примере, мы создаём три кнопки переключателя и QWidget. Мы устанавливаем чёрный цвет фона. Кнопки переключателей будут переключать красные, зелёные и синие части значений цвета. Цвет фона будет зависеть от того, на какие кнопки переключателей мы нажали.
Это начальное значение цвета (чёрный).
Чтобы создать кнопку переключателя, мы создаём QPushButton и делаем её проверяемой, путём вызова метода setCheckable().
Мы привязываем сигнал к нашему пользовательскому методу. Мы используем сигнал clicked, который работает с логическим значением.
Мы получаем кнопку, которая была переключена.
В случае кнопки red, мы обновляем красную часть цвета соответственно.
Мы используем таблицы стилей, чтобы менять цвет фона.
QSlider (ползунок)
Qslider – ползунок (виджет, который имеет простой регулятор). Этот регулятор может быть утянут назад и вперёд. Таким способом, мы выбираем значение для конкретной задачи. Иногда, использование ползунка более естественно, чем ввод числа или использование переключателя-счётчика. В нашем примере, мы покажем один ползунок и одну метку. Метка будет показывать изображение. Ползунок будет контролировать метку.
В нашем примере, мы симулируем контроль громкости. Путём перетаскивания регулятора ползунка, мы меняем изображение на метке.
Здесь мы создаём горизонтальный ползунок.
Мы создаём виджет QLabel и устанавливаем начальное изображение «Mute» на него.
Мы привязываем сигнал valueChanged к определенному нами методу changeValue().
Основываясь на значении ползунка, мы устанавливаем изображение на метку. В коде выше, мы устанавливаем изображение mute.png на метку, если ползунок приравнен к нулю.
QProgressBar (прогресс бар)
QProgressBar – прогресс бар (виджет, который используется, когда мы обрабатываем продолжительные задачи). Он анимирует процесс, чтобы пользователи знали, что задача продвигается. Мы можем установить минимальное и максимальное значение для прогресс бара. Значения по умолчанию – 0 и 99.
В нашем примере, мы имеем горизонтальный индикатор прогресса и кнопку. Кнопка запускает и останавливает индикатор прогресса.
Это конструктор QProgressBar.
Чтобы активировать индикатор прогресса, мы используем объект таймера.
Чтобы запустить событие таймера, мы вызываем его методом start(). Этот метод имеет два параметра: таймаут, и объект, который будет принимать события.
Каждый QObject и его наследники имеют обработчик событий timerEvent(). Для того, чтобы реагировать на события таймера, мы переопределяем обработчик событий.
Внутри метода doAction(), мы запускаем и останавливаем таймер.
QCalendarWidget (виджет календаря)
QCalendarWidget предоставляет виджет помесячного календаря. Он позволяет пользователю выбирать дату простым и интуитивно-понятным способом.
Пример имеет виджет календаря и виджет метки. Текущая выбранная дата отображается в виджете метки.
Если мы выбираем дату из виджета, срабатывает сигнал clicked[QDate]. Мы присоединяем этот сигнал к пользовательскому методу showDate().
Мы возвращаем выбранную дату путём вызова метода selectedDate(). Тогда мы превращаем объект даты в строку и устанавливаем его в виджет метки.
В этой части руководства PyQt5, мы изучили некоторые виджеты.
Источник
Отслеживаем прогресс выполнения в Python
Индикаторы прогресса (progress bar) — визуальное отображение процесса работы. Они избавляют нас от необходимости беспокоиться о том, не завис ли скрипт, дают интуитивное представление о скорости его выполнения и подсказывают, сколько времени осталось до завершения.
Человек ранее не использовавший индикаторы прогресса может предположить, что их внедрение может сильно усложнить код. К счастью, это не так. Небольшие примеры ниже покажут, как быстро и просто начать отслеживать прогресс в консоли или в интерфейсе быстро набирающей популярность графической библиотеки PySimpleGUI.
Используем Progress
Первым у нас идёт модуль Progress.
Всё, что от вас потребуется, это указать количество ожидаемых итераций, тип индикатора и вызывать функцию при каждой итерации:
Есть индикаторы на любой вкус:
Используем tqdm
Следующей на очереди идёт библиотека tqdm.
Быстрый и расширяемый индикатор прогресса для Python и CLI
Всего один вызов функции понадобится для получения результата аналогичного предыдущему:
Само собой, в комплекте идёт куча настроек и опций.
Используем alive-progress
Ещё один вариант синтаксиса, побольше дефолтных анимаций, чем в предыдущих примерах:
GUI индикатор прогресса для скрипта
Иногда возникает необходимость предоставить конечному пользователю графический индикатор.
Сколько кода нужно, чтобы достигнуть такого результата? Немного:
Индикатор в приложении PySimpleGUI
Рассмотрим реализацию индикатора в PySimpleGUI.
Вот как это сделать:
Заключение
Как видите, нет ничего сложного в добавлении информации о прогрессе выполнения: кода немного, а отзывчивость повышается очень сильно. Используйте индикаторы, чтобы больше никогда не гадать, завис ли процесс или нет!
Источник
Qt Documentation
Table of Contents
Previous topic
Next topic
Quick search
QProgressBarВ¶
The QProgressBar widget provides a horizontal or vertical progress bar. More…
SynopsisВ¶
FunctionsВ¶
Virtual functionsВ¶
SlotsВ¶
def setRange (minimum, maximum)
SignalsВ¶
Detailed DescriptionВ¶
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.
The default value is “%p%”.
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.
The default value is “%p%”.
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.
The default value is “%p%”.
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
arg__1 – Orientation
This property holds the orientation of the progress bar.
The orientation must be Horizontal (the default) or Vertical .
minimum – int
maximum – int
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
В© 2020 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.
Источник