MainWindow.py (Código)

# -*- coding: utf-8 -*-
"""Python e Qt 6: PyQt6 QScrollBar()."""
from pathlib import Path
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import (QApplication, QListWidget, QMainWindow,
                             QScrollBar, QVBoxLayout, QWidget)
# Informações do aplicativo.
APPLICATION_NAME = 'br.natorsc.Exemplo'
ORGANIZATION_NAME = APPLICATION_NAME.split('.')[1]
ORGANIZATION_DOMAIN = '.'.join(APPLICATION_NAME.split('.')[0:2])
BASE_DIR = Path(__file__).resolve().parent
ROOT_DIR = BASE_DIR.parent.parent
window_icon = str(ROOT_DIR.joinpath('assets', 'icons', 'icon-256x256.png'))
window_title = 'Python e Qt 6: PyQt6 QScrollBar().'
class MainWindow(QMainWindow):
    def __init__(self, application):
        super().__init__()
        self.application = application
        # Informações do monitor principal.
        primary_screen = self.application.primaryScreen()
        primary_screen_geometry = primary_screen.geometry()
        primary_screen_height = primary_screen_geometry.height()
        primary_screen_width = primary_screen_geometry.width()
        # Configurando a janela.
        # Definindo o tamanho da janela de forma dinâmica.
        window_width = int(primary_screen_width / 2)
        window_height = int(primary_screen_height / 2)
        # Configurando a posição e tamanho.
        self.setGeometry(0, 0, window_width, window_height)
        # Tamanho minimo da janela.
        self.setMinimumSize(window_width, window_height)
        # Tamanho maximo da janela.
        self.setMaximumSize(window_width + 200, window_height + 200)
        # Titulo da janela.
        self.setWindowTitle(window_title)
        # Ícone da janela
        self.setWindowIcon(QIcon(window_icon))
        # Layout do central_widget.
        vbox = QVBoxLayout()
        # Widget central.
        central_widget = QWidget()
        # Definindo o layout do widget central.
        central_widget.setLayout(vbox)
        # Adicionando o widget central.
        self.setCentralWidget(central_widget)
        # O seu código aqui:
        self.scrollbar = QScrollBar()
        # Sinal é emitido quando o scrollbar é arrastado com o mouse.
        self.scrollbar.sliderMoved.connect(self.on_slider_moved)
        # Sinal é emitido quando os botões do scrollbar são clicados.
        self.scrollbar.valueChanged.connect(self.on_slider_moved)
        listwidget = QListWidget()
        listwidget.setVerticalScrollBar(self.scrollbar)
        vbox.addWidget(listwidget)
        for n in range(1, 100):
            listwidget.addItem(f'Item {n}')
        # Exibindo a janela.
        self.show()
    def on_slider_moved(self, scrollbar_value):
        print(f'Valor atual do QScrollBar: {scrollbar_value}')
        print(f'Valor minimo do QScrollBar: {self.scrollbar.minimum()}')
        print(f'Valor maximo do QScrollBar: {self.scrollbar.maximum()}\n')
if __name__ == "__main__":
    import sys
    # Verificando a plataforma onde o código está sendo executado.
    if sys.platform == 'win32' or sys.platform == 'win64':
        from ctypes import windll
        # Para exibir o ícone na taskbar (barra de tarefas) do windows.
        windll.shell32.SetCurrentProcessExplicitAppUserModelID(APPLICATION_NAME)
    elif sys.platform == 'linux':
        from os import environ, getenv
        # Definindo o tipo de sessão onde o código será executado.
        if getenv('XDG_SESSION_TYPE') == 'wayland':
            environ['QT_QPA_PLATFORM'] = 'wayland'
        elif getenv('XDG_SESSION_TYPE') is None:
            # Funciona bem no Chrome OS.
            environ['QT_QPA_PLATFORM'] = 'xcb'
    application = QApplication(sys.argv)
    application.setOrganizationName(ORGANIZATION_NAME)
    application.setOrganizationDomain(ORGANIZATION_DOMAIN)
    application.setApplicationName(APPLICATION_NAME)
    application.setDesktopFileName(f'{APPLICATION_NAME}.desktop')
    window = MainWindow(application=application)
    sys.exit(application.exec())