MainWindow.py (Código)

# -*- coding: utf-8 -*-
"""Python e Qt 6: PyQt6 QRadioButton()."""
from pathlib import Path
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import (QApplication, QButtonGroup, QGroupBox,
                             QMainWindow, QRadioButton, 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 QRadioButton().'
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()
        # vbox.addStretch(True)
        vbox.setAlignment(Qt.AlignmentFlag.AlignTop)
        # 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:
        # Layout que será utilizado dentro do groupbox.
        groupbox_vbox = QVBoxLayout()
        groupbox = QGroupBox()
        groupbox.setTitle('Selecione o gênero')
        groupbox.setLayout(groupbox_vbox)
        vbox.addWidget(groupbox)
        # QButtonGroup gerência quando o radio button é clicado.
        button_group = QButtonGroup(self)
        button_group.buttonClicked.connect(self.on_button_toggled)
        radio_button_male = QRadioButton()
        radio_button_male.setObjectName('male')
        radio_button_male.setText('Masculino')
        button_group.addButton(radio_button_male)
        groupbox_vbox.addWidget(radio_button_male)
        radio_button_female = QRadioButton()
        radio_button_female.setObjectName('female')
        radio_button_female.setText('Feminino')
        button_group.addButton(radio_button_female)
        groupbox_vbox.addWidget(radio_button_female)
        # Exibindo a janela.
        self.show()
    def on_button_toggled(self, radio_button):
        radio_button_text = radio_button.text()
        print(f'Texto do radio button: {radio_button_text}.')
        radio_button_object_name = radio_button.objectName()
        print(f'Nome do objecto: {radio_button_object_name}.')
        if radio_button_object_name == 'male':
            print(
                f'Faça algo específico com radio button {radio_button_text}.')
        elif radio_button_object_name == 'female':
            print(
                f'Faça algo específico com radio button {radio_button_text}.')
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())