Package QFlow
Sub-modules
QFlow.componentsQFlow.coreQFlow.helpersQFlow.hooksQFlow.modulesQFlow.storesQFlow.utils
Functions
def app(title: str,
geometry: list[int],
icon: Callable[[], PyQt6.QtGui.QIcon],
name: str = 'App',
resizable: bool = True,
maximizable: bool = True,
strictClosingWindows: bool = True,
opacity: float = 1.0,
animatedEvents: Dict[str, bool] = None,
animationValues: Dict[str, float] = None)-
Expand source code
def app( title: str, geometry: list[int], icon: Callable[[], QIcon], name: str = 'App', resizable: bool = True, maximizable: bool = True, strictClosingWindows: bool = True, opacity: float = 1.0, animatedEvents: Dict[str, bool] = None, animationValues: Dict[str, float] = None ): """ Initializes the App with application-specific settings. Args: title (str): The title to set for the application window. geometry (list): The window geometry as a list [x, y, width, height]. icon (Callable[[], QIcon]): Callable to make the icon to set for the window. name (str, optional): The name of the application window. Defaults to "App". resizable (bool, optional): Determines whether the window can be resized. Defaults to True. maximizable (bool, optional): Determines whether the window can be maximized. Defaults to True. strictClosingWindows (bool, optional): Determines whether all windows should be closed when the main window is closed. Defaults to True. opacity (float, optional): The opacity of the window. Defaults to 1.0. animatedEvents (Dict[str, bool], optional): Default animations for events. animationValues (Dict[str, float], optional): Default values for animations. """ def decorator(cls): originit = getattr(cls, '__init__', None) def newinit(self, *args, **kwargs): super(cls, self).__init__( title=title, geometry=geometry if geometry is not None else [], icon=icon, name=name, resizable=resizable, maximizable=maximizable, strictClosingWindows=strictClosingWindows, opacity=opacity, animatedEvents=animatedEvents if animatedEvents is not None else { 'fadeIn': False, 'fadeOut': False }, animationValues=animationValues if animationValues is not None else { 'opacityIncreasedIn': 0.02, 'opacityReductionOut': 0.02 } ) if originit: originit(self, *args, **kwargs) cls.__init__ = newinit return cls return decoratorInitializes the App with application-specific settings.
Args
title:str- The title to set for the application window.
geometry:list- The window geometry as a list [x, y, width, height].
icon:Callable[[], QIcon]- Callable to make the icon to set for the window.
name:str, optional- The name of the application window. Defaults to "App".
resizable:bool, optional- Determines whether the window can be resized. Defaults to True.
maximizable:bool, optional- Determines whether the window can be maximized. Defaults to True.
strictClosingWindows:bool, optional- Determines whether all windows should be closed when the main window is closed. Defaults to True.
opacity:float, optional- The opacity of the window. Defaults to 1.0.
animatedEvents:Dict[str, bool], optional- Default animations for events.
animationValues:Dict[str, float], optional- Default values for animations.
def screen(name: str, autoreloadUI: bool = False, autoUI: bool = True, parentType=None)-
Expand source code
def screen(name: str, autoreloadUI: bool = False, autoUI: bool = True, parentType = None): """ Initialize the Screen object. Args: name (str): The name to assign to the screen. autoreloadUI (bool): If True, ensures the class has a `UI` method and reloads it on show. autoUI (bool): Executes the UI function during the showEvent without having to call it. parentType: Expected parent type for validation. *args: Additional positional arguments. **kwargs: Additional keyword arguments. """ def decorator(cls): originit = getattr(cls, '__init__', None) def newinit(self, *args, **kwargs): super(cls, self).__init__( name=name, autoreloadUI=autoreloadUI, autoUI=autoUI, parentType=parentType ) self.args = { 'name': name, 'autoreloadUI': autoreloadUI, 'autoUI': autoUI, 'parentType': parentType } if originit: originit(self, *args, **kwargs) cls.__init__ = newinit return cls return decoratorInitialize the Screen object.
Args
name:str- The name to assign to the screen.
autoreloadUI:bool- If True, ensures the class has a
UImethod and reloads it on show. autoUI:bool- Executes the UI function during the showEvent without having to call it.
parentType- Expected parent type for validation.
*args- Additional positional arguments.
**kwargs- Additional keyword arguments.
def window(name: str = '',
title: str = '',
geometry: list[int] = None,
maximizable: bool = True,
icon: Callable[[], PyQt6.QtGui.QIcon] = None,
parentType=None,
resizable: bool = True,
strictClosingWindows: bool = True,
opacity: float = 1.0,
animatedEvents: Dict[str, bool] = None,
animationValues: Dict[str, float] = None)-
Expand source code
def window( name: str = '', title: str = '', geometry: list[int] = None, maximizable: bool = True, icon: Callable[[], QIcon] = None, parentType=None, resizable: bool = True, strictClosingWindows: bool = True, opacity: float = 1.0, animatedEvents: Dict[str, bool] = None, animationValues: Dict[str, float] = None ): """ Initializes the Window with specified properties and screen management. Args: name (str): The name of the window. title (str): The title of the window. geometry (list): The geometry of the window (ax: int, ay: int, aw: int, ah: int). maximizable (bool, optional): Determines whether the window can be maximized. Defaults to True. icon (Callable[[], QIcon]): Callable to make the icon to set for the window. parentType: Expected parent type for validation. resizable (bool, optional): The ability to resize the window. Defaults to True. strictClosingWindows (bool, optional): Determines whether all windows should be closed when the window is closed. Defaults to True. opacity (float, optional): The opacity of the window. animatedEvents (Dict[str, bool], optional): Default animations for events. animationValues (Dict[str, float], optional): Default values for animations. """ def decorator(cls): originit = getattr(cls, '__init__', None) def newinit(self, *args, **kwargs): super(cls, self).__init__( name=name, title=title, geometry=geometry if geometry is not None else [], maximizable=maximizable, icon=icon, parent=None, parentType=parentType, resizable=resizable, strictClosingWindows=strictClosingWindows, opacity=opacity, animatedEvents=animatedEvents if animatedEvents is not None else { 'fadeIn': False, 'fadeOut': False }, animationValues=animationValues if animationValues is not None else { 'opacityIncreasedIn': 0.02, 'opacityReductionOut': 0.02 } ) self.args = { 'name': name, 'title': title, 'geometry': geometry if geometry is not None else [], 'maximizable': maximizable, 'icon': icon, 'parentType': parentType, 'resizable': resizable, 'strictClosingWindows': strictClosingWindows, 'opacity': opacity, 'animatedEvents': animatedEvents if animatedEvents is not None else { 'fadeIn': False, 'fadeOut': False }, 'animationValues': animationValues if animationValues is not None else { 'opacityIncreasedIn': 0.02, 'opacityReductionOut': 0.02 } } if originit: originit(self, *args, **kwargs) cls.__init__ = newinit return cls return decoratorInitializes the Window with specified properties and screen management.
Args
name:str- The name of the window.
title:str- The title of the window.
geometry:list- The geometry of the window (ax: int, ay: int, aw: int, ah: int).
maximizable:bool, optional- Determines whether the window can be maximized. Defaults to True.
icon:Callable[[], QIcon]- Callable to make the icon to set for the window.
parentType- Expected parent type for validation.
resizable:bool, optional- The ability to resize the window. Defaults to True.
strictClosingWindows:bool, optional- Determines whether all windows should be closed when the window is closed. Defaults to True.
opacity:float, optional- The opacity of the window.
animatedEvents:Dict[str, bool], optional- Default animations for events.
animationValues:Dict[str, float], optional- Default values for animations.
Classes
class App (title: str,
geometry: list[int],
icon: Callable[[], PyQt6.QtGui.QIcon],
name: str = 'App',
resizable: bool = True,
maximizable: bool = True,
strictClosingWindows: bool = True,
opacity: float = 1.0,
animatedEvents: Dict[str, bool] = None,
animationValues: Dict[str, float] = None)-
Expand source code
class App(Window): """ An application class that extends Window functionality for main application windows. This class provides all the functionality of a Window plus additional application-level features like strict window management and enhanced screen handling. """ def __init__( self, title: str, geometry: list[int], icon: Callable[[], QIcon], name: str = 'App', resizable: bool = True, maximizable: bool = True, strictClosingWindows: bool = True, opacity: float = 1.0, animatedEvents: Dict[str, bool] = None, animationValues: Dict[str, float] = None ): """ Initializes the App with application-specific settings. Args: title (str): The title to set for the application window. geometry (list): The window geometry as a list [x, y, width, height]. icon (Callable[[], QIcon]): Callable to make the icon to set for the window. name (str, optional): The name of the application window. Defaults to "App". resizable (bool, optional): Determines whether the window can be resized. Defaults to True. maximizable (bool, optional): Determines whether the window can be maximized. Defaults to True. strictClosingWindows (bool, optional): Determines whether all windows should be closed when the main window is closed. Defaults to True. opacity (float, optional): The opacity of the window. Defaults to 1.0. animatedEvents (Dict[str, bool], optional): Default animations for events. animationValues (Dict[str, float], optional): Default values for animations. """ # Initialize the parent Window class super().__init__( name=name, title=title, geometry=geometry, icon=icon, parent=None, parentType=None, resizable=resizable, strictClosingWindows=strictClosingWindows, opacity=opacity, animatedEvents=animatedEvents, animationValues=animationValues, maximizable=maximizable ) # Application-specific properties self.maximizable = maximizable # Configure window properties self._configureWindowProperties(resizable, maximizable, geometry) # Set up close event handler self.closeEvent = self._onAppClose def _configureWindowProperties(self, resizable: bool, maximizable: bool, geometry: list[int]) -> None: """ Configures window properties based on the provided settings. Args: resizable (bool): Whether the window should be resizable. maximizable (bool): Whether the window should be maximizable. geometry (list[int]): The window geometry. """ if not resizable: # The last two indices of the geometry are width and height width, height = geometry[-2:] self.setFixedSize(width, height) self.setWindowFlags(Qt.WindowType.WindowMinimizeButtonHint | Qt.WindowType.WindowCloseButtonHint) if not maximizable: currentFlags = self.windowFlags() # Remove maximize button while keeping other flags newFlags = currentFlags & ~Qt.WindowType.WindowMaximizeButtonHint self.setWindowFlags(newFlags | Qt.WindowType.WindowMinimizeButtonHint | Qt.WindowType.WindowCloseButtonHint) def _onWindowClose(self, event, name: str) -> None: """ Handles window close events with application-specific logic. Args: event: The close event. name (str): The name of the window being closed. """ if self.strictClosingWindows: # Close all child windows when any window is closed for windowName, window_instance in list(self.windows.items()): if windowName != name: # Don't close the window that's already closing window_instance.close() # Remove the window from management after a short delay QTimer.singleShot(0, lambda: self.removeWindow(name)) event.accept() def _onAppClose(self, event) -> None: """ Handles the main application close event. Args: event: The close event. """ if self.strictClosingWindows: # Close all managed windows when the main application closes for _, window in self.windows.items(): window.close() event.accept() def run(self, QApp: QApplication): self.show() sys.exit(QApp.exec())An application class that extends Window functionality for main application windows.
This class provides all the functionality of a Window plus additional application-level features like strict window management and enhanced screen handling.
Initializes the App with application-specific settings.
Args
title:str- The title to set for the application window.
geometry:list- The window geometry as a list [x, y, width, height].
icon:Callable[[], QIcon]- Callable to make the icon to set for the window.
name:str, optional- The name of the application window. Defaults to "App".
resizable:bool, optional- Determines whether the window can be resized. Defaults to True.
maximizable:bool, optional- Determines whether the window can be maximized. Defaults to True.
strictClosingWindows:bool, optional- Determines whether all windows should be closed when the main window is closed. Defaults to True.
opacity:float, optional- The opacity of the window. Defaults to 1.0.
animatedEvents:Dict[str, bool], optional- Default animations for events.
animationValues:Dict[str, float], optional- Default values for animations.
Ancestors
- QFlow.modules.window.window.Window
- PyQt6.QtWidgets.QMainWindow
- PyQt6.QtWidgets.QWidget
- PyQt6.QtCore.QObject
- PyQt6.sip.wrapper
- PyQt6.QtGui.QPaintDevice
- PyQt6.sip.simplewrapper
Subclasses
Methods
def run(self, QApp: PyQt6.QtWidgets.QApplication)-
Expand source code
def run(self, QApp: QApplication): self.show() sys.exit(QApp.exec())
class Screen (name: str,
autoreloadUI: bool = False,
autoUI: bool = True,
parentType=None,
*args,
**kwargs)-
Expand source code
class Screen(QWidget): """ A class that provides screen properties and screen management capabilities. Can be used as a base class or through composition. """ def __init__(self, name: str, autoreloadUI: bool = False, autoUI: bool = True, parentType = None, *args, **kwargs): """ Initialize the Screen object. Args: name (str): The name to assign to the screen. autoreloadUI (bool): If True, ensures the class has a `UI` method and reloads it on show. autoUI (bool): Executes the UI function during __init__ without having to call it. parentType: Expected parent type for validation. *args: Additional positional arguments. **kwargs: Additional keyword arguments. """ super().__init__(*args, **kwargs) self.name = name self.args = {} """ Dictionary with the arguments passed from the screen decorator. """ self.screenName = self.name self.parentType = parentType self._autoreloadUI = autoreloadUI self._autoUI = autoUI self._loaded = False if autoreloadUI: # Check if the class has a UI method if not hasattr(self, 'UI') or not callable(getattr(self, 'UI')): raise TypeError(f'The class {self.__class__.__name__} must have a UI() method') # Store original parent method if it exists if hasattr(super(), 'parent'): originalParent = super().parent # Get the real parent, not the QStackedWidget parent = originalParent() self.parent = lambda: parent # Validate parent type if specified if parentType is not None and hasattr(self, 'parent'): parent = self.parent() if parent and hasattr(parent, '__class__') and hasattr(parent.__class__, '__bases__'): if parent.__class__.__bases__[0] != parentType: raise TypeError( f"Screen '{name}' only accepts the parentType '{parentType}' not '{parent.__class__.__bases__[0]}'" ) def parent(self) -> Window: ... @staticmethod def removeAllLayouts(widget: QWidget): """ Recursively removes all layouts and widgets from a given QWidget. Args: widget (QWidget): The widget from which all layouts and child widgets will be removed. """ layout = widget.layout() if layout is not None: while layout.count(): item = layout.takeAt(0) if item.widget(): item.widget().setParent(None) if item.layout(): Screen.removeAllLayouts(item.layout()) layout.deleteLater() def reloadUI(self): """ Reloads the interface. """ if not hasattr(self, 'UI') or not callable(getattr(self, 'UI')): raise TypeError(f'The class {self.__class__.__name__} must have a UI() method') Screen.removeAllLayouts(self) QTimer.singleShot(0, lambda: self.UI()) def setScreenName(self, name: str) -> None: """ Changes the name of the screen. Args: name (str): The new name for the screen. Raises: ValueError: If name is empty or not a string. """ if not name: raise ValueError("Screen name must be a non-empty string") self.name = name self.screenName = name def showEvent(self, event): """ Override showEvent to handle UI reloading and effects. Args: event: The show event. """ if self._autoreloadUI: # Reload the UI after a short delay. Note: This line cost me 5 hours of debugging. QTimer.singleShot(0, lambda: self.reloadUI()) if not self._autoreloadUI and self._autoUI and not self._loaded: # Execute the UI if autoUI QTimer.singleShot(0, lambda: self.UI()) # Specifies that the screen has already been loaded self._loaded = True if hasattr(self, 'effect'): self.effect() # Call parent's showEvent if it exists if hasattr(super(), 'showEvent'): super().showEvent(event)A class that provides screen properties and screen management capabilities. Can be used as a base class or through composition.
Initialize the Screen object.
Args
name:str- The name to assign to the screen.
autoreloadUI:bool- If True, ensures the class has a
UImethod and reloads it on show. autoUI:bool- Executes the UI function during init without having to call it.
parentType- Expected parent type for validation.
*args- Additional positional arguments.
**kwargs- Additional keyword arguments.
Ancestors
- PyQt6.QtWidgets.QWidget
- PyQt6.QtCore.QObject
- PyQt6.sip.wrapper
- PyQt6.QtGui.QPaintDevice
- PyQt6.sip.simplewrapper
Subclasses
Static methods
def removeAllLayouts(widget: PyQt6.QtWidgets.QWidget)-
Expand source code
@staticmethod def removeAllLayouts(widget: QWidget): """ Recursively removes all layouts and widgets from a given QWidget. Args: widget (QWidget): The widget from which all layouts and child widgets will be removed. """ layout = widget.layout() if layout is not None: while layout.count(): item = layout.takeAt(0) if item.widget(): item.widget().setParent(None) if item.layout(): Screen.removeAllLayouts(item.layout()) layout.deleteLater()Recursively removes all layouts and widgets from a given QWidget.
Args
widget:QWidget- The widget from which all layouts and child widgets will be removed.
Instance variables
var args-
Dictionary with the arguments passed from the screen decorator.
Methods
def parent(self) ‑> QFlow.modules.window.window.Window-
Expand source code
def parent(self) -> Window: ...parent(self) -> Optional[QObject]
def reloadUI(self)-
Expand source code
def reloadUI(self): """ Reloads the interface. """ if not hasattr(self, 'UI') or not callable(getattr(self, 'UI')): raise TypeError(f'The class {self.__class__.__name__} must have a UI() method') Screen.removeAllLayouts(self) QTimer.singleShot(0, lambda: self.UI())Reloads the interface.
def setScreenName(self, name: str) ‑> None-
Expand source code
def setScreenName(self, name: str) -> None: """ Changes the name of the screen. Args: name (str): The new name for the screen. Raises: ValueError: If name is empty or not a string. """ if not name: raise ValueError("Screen name must be a non-empty string") self.name = name self.screenName = nameChanges the name of the screen.
Args
name:str- The new name for the screen.
Raises
ValueError- If name is empty or not a string.
def showEvent(self, event)-
Expand source code
def showEvent(self, event): """ Override showEvent to handle UI reloading and effects. Args: event: The show event. """ if self._autoreloadUI: # Reload the UI after a short delay. Note: This line cost me 5 hours of debugging. QTimer.singleShot(0, lambda: self.reloadUI()) if not self._autoreloadUI and self._autoUI and not self._loaded: # Execute the UI if autoUI QTimer.singleShot(0, lambda: self.UI()) # Specifies that the screen has already been loaded self._loaded = True if hasattr(self, 'effect'): self.effect() # Call parent's showEvent if it exists if hasattr(super(), 'showEvent'): super().showEvent(event)Override showEvent to handle UI reloading and effects.
Args
event- The show event.
class Window (name: str = '',
title: str = '',
geometry: list[int] = [],
maximizable=True,
icon: Callable[[], QIcon] = [],
parent=None,
parentType=None,
resizable: bool = True,
strictClosingWindows: bool = True,
opacity: float = 1.0,
animatedEvents: Dict[str, bool] = None,
animationValues: Dict[str, float] = None)-
Expand source code
class Window(QMainWindow): """ A window class that provides window properties and screen management capabilities. This class allows you to configure the title, geometry, and icon of a window, while also providing built-in screen management functionality. """ def __init__( self, name: str = '', title: str = '', geometry: list[int] = [], maximizable=True, icon: Callable[[], QIcon] = [], parent=None, parentType=None, resizable: bool = True, strictClosingWindows: bool = True, opacity: float = 1.0, animatedEvents: Dict[str, bool] = None, animationValues: Dict[str, float] = None ): """ Initializes the Window with specified properties and screen management. Args: name (str): The name of the window. title (str): The title of the window. geometry (list): The geometry of the window (ax: int, ay: int, aw: int, ah: int). maximizable (bool, optional): Determines whether the window can be maximized. Defaults to True. icon (Callable[[], QIcon]): Callable to make the icon to set for the window. parent: Parent widget. parentType: Expected parent type for validation. resizable (bool, optional): The ability to resize the window. Defaults to True. strictClosingWindows (bool, optional): Determines whether all windows should be closed when the window is closed. Defaults to True. opacity (float, optional): The opacity of the window. animatedEvents (Dict[str, bool], optional): Default animations for events to {'fadeIn': False, 'fadeOut': False}. animationValues (Dict[str, float], optional): Default values for animations {'opacityIncreasedIn': 0.02, 'opacityReductionOut': 0.02}. """ super().__init__(parent) # Initialize window properties self.name = name self.title = title self.windowGeometry = geometry self.icon = icon self.args = {} """ Dictionary with the arguments passed from the window decorator. """ # Initialize screen management self.screenHistory = [] self.screens = {} self.stackedScreens = QStackedWidget() self.windows = {} self.strictClosingWindows = strictClosingWindows self.msRenderTime = 16 # Configure window self.setWindowTitle(self.title) self.setGeometry(*self.windowGeometry) if not resizable: # The last two indices of the geometry are width and height width, height = geometry[-2:] self.setFixedSize(width, height) self.setWindowFlags(Qt.WindowType.WindowMinimizeButtonHint | Qt.WindowType.WindowCloseButtonHint) if not maximizable: currentFlags = self.windowFlags() # Remove maximize button while keeping other flags newFlags = currentFlags & ~Qt.WindowType.WindowMaximizeButtonHint self.setWindowFlags(newFlags | Qt.WindowType.WindowMinimizeButtonHint | Qt.WindowType.WindowCloseButtonHint) self.setWindowIcon(icon()) self.setCentralWidget(self.stackedScreens) if opacity != 1.0: self.setWindowOpacity(opacity) self.opacity = opacity # Initialize animation settings self._animationValues = { 'opacityIncreasedIn': 0.02, 'opacityReductionOut': 0.02 } if animationValues: self._animationValues.update(animationValues) self._animatedEvents = { 'fadeIn': False, 'fadeOut': False } if animatedEvents: self._animatedEvents.update(animatedEvents) # Validate parent type if specified if parentType is not None and parent is not None: if type(parent) != parentType: raise TypeError( f"Window '{name}' only accepts the parentType '{parentType}' not '{type(parent)}'" ) def addScreen(self, screen: QWidget) -> None: """ Adds a screen widget to the window's stacked widget. This method checks that the screen has a valid 'screenName' attribute and adds it to the stacked widget for navigation. Args: screen (QWidget): The screen widget to add to the stacked widget. Raises: Exception: If the screen does not have a 'screenName' attribute. """ if not hasattr(screen, 'screenName'): raise Exception(f'{screen} does not have screenName attribute.') name = screen.screenName self.screens[name] = screen self.stackedScreens.addWidget(screen) def setScreen(self, name: str, args: dict = None) -> None: """ Sets the current screen to display based on the screen name. This method accepts a string name that must match the 'screenName' attribute of a previously added screen. Args: name (str): The name of the screen to display. args (dict): Arguments for the screen. Raises: Exception: If the specified screen does not exist. """ if name in self.screens: currentScreen = self.stackedScreens.currentWidget() if currentScreen: self.screenHistory.append(currentScreen) screen = self.screens[name] if not hasattr(screen, 'screenName'): raise Exception(f'The screen `{screen}` does not have screenName attribute.') if args: INSTANCE_ARGS.setArgs(instance=screen, args=args) self.stackedScreens.setCurrentWidget(screen) else: raise Exception(f'The screen `{name}` does not exist.') def goBack(self) -> None: """ Navigates back to the previous screen in the screen history. """ if self.screenHistory: previousScreen = self.screenHistory.pop() self.stackedScreens.setCurrentWidget(previousScreen) def setWindowName(self, name: str) -> None: """ Changes the name of the window. Args: name (str): The new name for the window. Raises: ValueError: If name is empty or not a string. """ if not name: raise ValueError("Window name must be a non-empty string") self.name = name def _animateFadeOut(self) -> None: """ Animates the window fade out effect. """ timer = QTimer(self) opacity = self.windowOpacity() def _modifyOpacity(): nonlocal opacity opacity -= self._animationValues['opacityReductionOut'] if opacity <= 0.2: timer.stop() self.setWindowOpacity(opacity) timer.timeout.connect(_modifyOpacity) timer.start(self.msRenderTime) def _animateFadeIn(self) -> None: """ Animates the window fade in effect. """ if not self._animatedEvents['fadeOut']: self.setWindowOpacity(0.2) timer = QTimer(self) opacity = self.windowOpacity() def _modifyOpacity(): nonlocal opacity opacity += self._animationValues['opacityIncreasedIn'] if opacity >= self.opacity: timer.stop() self.setWindowOpacity(opacity) timer.timeout.connect(_modifyOpacity) timer.start(self.msRenderTime) def changeEvent(self, event): """ Handles window state change events for animations. Args: event: The change event. """ if event.type() == QEvent.Type.WindowStateChange: if self.windowState() == Qt.WindowState.WindowMinimized: if self._animatedEvents['fadeOut']: self._animateFadeOut() elif self.windowState() == Qt.WindowState.WindowNoState: if self._animatedEvents['fadeIn']: self._animateFadeIn() else: self.setWindowOpacity(self.opacity) def existScreen(self, name: str) -> bool: """ Checks if a screen exists in the window. Args: name (str): The name of the screen. Returns: bool: True if the screen exists, False if it does not exist. """ return name in self.screens def reloadScreens(self) -> None: """ Reloads all window screens. """ for name, screen in self.screens.items(): if self.existScreen(name): screen.reloadUI() def reloadScreen(self, name: str) -> None: """ Reloads a screen of the window. Args: name (str): The name of the screen to reload. """ if self.existScreen(name): screen = self.screens[name] screen.reloadUI() def createWindow(self, window: "Window", args: dict = None) -> None: """ Creates a new window and adds it to the windows dictionary for management. The window is created using the attributes 'windowGeometry', 'title', and 'name' of the specified Window instance. Args: window (Window): The window to create. args (dict): Arguments for the window. Raises: Exception: If the window is missing any of the required attributes. """ geometry = getattr(window, 'windowGeometry', None) title = getattr(window, 'title', None) name = getattr(window, 'name', None) if not geometry: raise Exception(f"The window '{window}' does not have a valid <windowGeometry>.") if not title: raise Exception(f"The window '{window}' does not have a valid <title>.") if not name: raise Exception(f"The window '{window}' does not have a valid <name>.") if not hasattr(self, 'windows'): self.windows = {} if not self.windows.get(name): window.closeEvent = lambda event: self.onWindowClose(event, name) self.windows[name] = window window.setGeometry(*geometry) window.setWindowTitle(title) if args: INSTANCE_ARGS.setArgs(instance=window, args=args) # Execute effect if hasattr(window, 'effect'): window.effect() window.show() else: print(f"The window '{name}' already exists.") def onWindowClose(self, event, name: str) -> None: """ Handles the window close event and removes the window from the windows list. Args: event: The close event. name (str): The name of the window being closed. """ if self.strictClosingWindows: for _, window in self.windows.items(): window.close() QTimer.singleShot(0, lambda: self.removeWindow(name)) event.accept() def removeWindow(self, name: str) -> None: """ Removes a window from the windows list. Args: name (str): The name of the window to remove. """ if name in self.windows: del self.windows[name] def setWindow(self, name: str, args: dict = None) -> None: """ Brings a specified window to the front and activates it. Args: name (str): The name of the window to bring to the front. args (dict): Arguments for the window. Raises: Exception: If the specified window does not exist. """ if name in self.windows: self.windows[name].raise_() self.windows[name].activateWindow() if args: INSTANCE_ARGS.setArgs(instance=self.windows[name], args=args) # Execute effect if hasattr(self.windows[name], 'effect'): self.windows[name].effect() else: raise Exception(f"The window '{name}' does not exist.") def closeWindow(self, name: str) -> None: """ Closes a specified window. Args: name (str): The name of the window to close. Raises: Exception: If the specified window does not exist. """ if name in self.windows: self.windows[name].close() del self.windows[name] else: raise Exception(f"The window '{name}' does not exist.") def removeScreen(self, name: str) -> None: """ Removes a screen from the screens list. Args: name (str): The name of the screen to remove. Raises: Exception: If the screen does not exist. """ if name not in self.screens: raise Exception(f"The screen '{name}' does not exist.") if hasattr(self, 'stackedScreens'): self.stackedScreens.removeWidget(self.screens[name]) self.screens.pop(name) def existWindow(self, name: str) -> bool: """ Checks if a window exists in the main window. Args: name (str): The name of the window. Returns: bool: True if the window exists, False if it does not exist. """ return name in self.windows def reloadWindowScreens(self, window: str) -> None: """ Reloads the screens of a window. Args: window (str): The name of the window to reload. """ targetWindow: Window = self.windows.get(window) if targetWindow: targetWindow.reloadScreens() def reloadWindowScreen(self, window: str, screen: str) -> None: """ Reloads a screen of a window. Args: window (str): The name of the window to reload. screen (str): The name of the screen to reload. """ targetWindow: Window = self.windows.get(window) if targetWindow: targetWindow.reloadScreen(screen) def getScreenHistory(self) -> list: """ Returns the current screen navigation history. Returns: list: List of screens in navigation history. """ return self.screenHistory.copy() def clearScreenHistory(self) -> None: """ Clears the screen navigation history. """ self.screenHistory.clear() def getCurrentScreen(self) -> QWidget: """ Gets the currently active screen. Returns: QWidget: The currently active screen widget. """ return self.stackedScreens.currentWidget() def getAllScreens(self) -> Dict[str, QWidget]: """ Gets all registered screens. Returns: Dict[str, QWidget]: Dictionary of all registered screens. """ return self.screens.copy() def getAllWindows(self) -> Dict[str, "Window"]: """ Gets all managed windows. Returns: Dict[str, Window]: Dictionary of all managed windows. """ return self.windows.copy()A window class that provides window properties and screen management capabilities.
This class allows you to configure the title, geometry, and icon of a window, while also providing built-in screen management functionality.
Initializes the Window with specified properties and screen management.
Args
name:str- The name of the window.
title:str- The title of the window.
geometry:list- The geometry of the window (ax: int, ay: int, aw: int, ah: int).
maximizable:bool, optional- Determines whether the window can be maximized. Defaults to True.
icon:Callable[[], QIcon]- Callable to make the icon to set for the window.
parent- Parent widget.
parentType- Expected parent type for validation.
resizable:bool, optional- The ability to resize the window. Defaults to True.
strictClosingWindows:bool, optional- Determines whether all windows should be closed when the window is closed. Defaults to True.
opacity:float, optional- The opacity of the window.
animatedEvents:Dict[str, bool], optional- Default animations for events to {'fadeIn': False, 'fadeOut': False}.
animationValues:Dict[str, float], optional- Default values for animations {'opacityIncreasedIn': 0.02, 'opacityReductionOut': 0.02}.
Ancestors
- PyQt6.QtWidgets.QMainWindow
- PyQt6.QtWidgets.QWidget
- PyQt6.QtCore.QObject
- PyQt6.sip.wrapper
- PyQt6.QtGui.QPaintDevice
- PyQt6.sip.simplewrapper
Subclasses
- QFlow.modules.app.app.App
- QFlowSecondaryWindow
Instance variables
var args-
Dictionary with the arguments passed from the window decorator.
Methods
def addScreen(self, screen: QWidget) ‑> None-
Expand source code
def addScreen(self, screen: QWidget) -> None: """ Adds a screen widget to the window's stacked widget. This method checks that the screen has a valid 'screenName' attribute and adds it to the stacked widget for navigation. Args: screen (QWidget): The screen widget to add to the stacked widget. Raises: Exception: If the screen does not have a 'screenName' attribute. """ if not hasattr(screen, 'screenName'): raise Exception(f'{screen} does not have screenName attribute.') name = screen.screenName self.screens[name] = screen self.stackedScreens.addWidget(screen)Adds a screen widget to the window's stacked widget.
This method checks that the screen has a valid 'screenName' attribute and adds it to the stacked widget for navigation.
Args
screen:QWidget- The screen widget to add to the stacked widget.
Raises
Exception- If the screen does not have a 'screenName' attribute.
def changeEvent(self, event)-
Expand source code
def changeEvent(self, event): """ Handles window state change events for animations. Args: event: The change event. """ if event.type() == QEvent.Type.WindowStateChange: if self.windowState() == Qt.WindowState.WindowMinimized: if self._animatedEvents['fadeOut']: self._animateFadeOut() elif self.windowState() == Qt.WindowState.WindowNoState: if self._animatedEvents['fadeIn']: self._animateFadeIn() else: self.setWindowOpacity(self.opacity)Handles window state change events for animations.
Args
event- The change event.
def clearScreenHistory(self) ‑> None-
Expand source code
def clearScreenHistory(self) -> None: """ Clears the screen navigation history. """ self.screenHistory.clear()Clears the screen navigation history.
def closeWindow(self, name: str) ‑> None-
Expand source code
def closeWindow(self, name: str) -> None: """ Closes a specified window. Args: name (str): The name of the window to close. Raises: Exception: If the specified window does not exist. """ if name in self.windows: self.windows[name].close() del self.windows[name] else: raise Exception(f"The window '{name}' does not exist.")Closes a specified window.
Args
name:str- The name of the window to close.
Raises
Exception- If the specified window does not exist.
def createWindow(self,
window: "'Window'",
args: dict = None) ‑> None-
Expand source code
def createWindow(self, window: "Window", args: dict = None) -> None: """ Creates a new window and adds it to the windows dictionary for management. The window is created using the attributes 'windowGeometry', 'title', and 'name' of the specified Window instance. Args: window (Window): The window to create. args (dict): Arguments for the window. Raises: Exception: If the window is missing any of the required attributes. """ geometry = getattr(window, 'windowGeometry', None) title = getattr(window, 'title', None) name = getattr(window, 'name', None) if not geometry: raise Exception(f"The window '{window}' does not have a valid <windowGeometry>.") if not title: raise Exception(f"The window '{window}' does not have a valid <title>.") if not name: raise Exception(f"The window '{window}' does not have a valid <name>.") if not hasattr(self, 'windows'): self.windows = {} if not self.windows.get(name): window.closeEvent = lambda event: self.onWindowClose(event, name) self.windows[name] = window window.setGeometry(*geometry) window.setWindowTitle(title) if args: INSTANCE_ARGS.setArgs(instance=window, args=args) # Execute effect if hasattr(window, 'effect'): window.effect() window.show() else: print(f"The window '{name}' already exists.")Creates a new window and adds it to the windows dictionary for management.
The window is created using the attributes 'windowGeometry', 'title', and 'name' of the specified Window instance.
Args
window:Window- The window to create.
args:dict- Arguments for the window.
Raises
Exception- If the window is missing any of the required attributes.
def existScreen(self, name: str) ‑> bool-
Expand source code
def existScreen(self, name: str) -> bool: """ Checks if a screen exists in the window. Args: name (str): The name of the screen. Returns: bool: True if the screen exists, False if it does not exist. """ return name in self.screensChecks if a screen exists in the window.
Args
name:str- The name of the screen.
Returns
bool- True if the screen exists, False if it does not exist.
def existWindow(self, name: str) ‑> bool-
Expand source code
def existWindow(self, name: str) -> bool: """ Checks if a window exists in the main window. Args: name (str): The name of the window. Returns: bool: True if the window exists, False if it does not exist. """ return name in self.windowsChecks if a window exists in the main window.
Args
name:str- The name of the window.
Returns
bool- True if the window exists, False if it does not exist.
def getAllScreens(self) ‑> Dict[str, PyQt6.QtWidgets.QWidget]-
Expand source code
def getAllScreens(self) -> Dict[str, QWidget]: """ Gets all registered screens. Returns: Dict[str, QWidget]: Dictionary of all registered screens. """ return self.screens.copy()Gets all registered screens.
Returns
Dict[str, QWidget]- Dictionary of all registered screens.
def getAllWindows(self) ‑> Dict[str, QFlow.modules.window.window.Window]-
Expand source code
def getAllWindows(self) -> Dict[str, "Window"]: """ Gets all managed windows. Returns: Dict[str, Window]: Dictionary of all managed windows. """ return self.windows.copy() def getCurrentScreen(self) ‑> PyQt6.QtWidgets.QWidget-
Expand source code
def getCurrentScreen(self) -> QWidget: """ Gets the currently active screen. Returns: QWidget: The currently active screen widget. """ return self.stackedScreens.currentWidget()Gets the currently active screen.
Returns
QWidget- The currently active screen widget.
def getScreenHistory(self) ‑> list-
Expand source code
def getScreenHistory(self) -> list: """ Returns the current screen navigation history. Returns: list: List of screens in navigation history. """ return self.screenHistory.copy()Returns the current screen navigation history.
Returns
list- List of screens in navigation history.
def goBack(self) ‑> None-
Expand source code
def goBack(self) -> None: """ Navigates back to the previous screen in the screen history. """ if self.screenHistory: previousScreen = self.screenHistory.pop() self.stackedScreens.setCurrentWidget(previousScreen)Navigates back to the previous screen in the screen history.
def onWindowClose(self, event, name: str) ‑> None-
Expand source code
def onWindowClose(self, event, name: str) -> None: """ Handles the window close event and removes the window from the windows list. Args: event: The close event. name (str): The name of the window being closed. """ if self.strictClosingWindows: for _, window in self.windows.items(): window.close() QTimer.singleShot(0, lambda: self.removeWindow(name)) event.accept()Handles the window close event and removes the window from the windows list.
Args
event- The close event.
name:str- The name of the window being closed.
def reloadScreen(self, name: str) ‑> None-
Expand source code
def reloadScreen(self, name: str) -> None: """ Reloads a screen of the window. Args: name (str): The name of the screen to reload. """ if self.existScreen(name): screen = self.screens[name] screen.reloadUI()Reloads a screen of the window.
Args
name:str- The name of the screen to reload.
def reloadScreens(self) ‑> None-
Expand source code
def reloadScreens(self) -> None: """ Reloads all window screens. """ for name, screen in self.screens.items(): if self.existScreen(name): screen.reloadUI()Reloads all window screens.
def reloadWindowScreen(self, window: str, screen: str) ‑> None-
Expand source code
def reloadWindowScreen(self, window: str, screen: str) -> None: """ Reloads a screen of a window. Args: window (str): The name of the window to reload. screen (str): The name of the screen to reload. """ targetWindow: Window = self.windows.get(window) if targetWindow: targetWindow.reloadScreen(screen)Reloads a screen of a window.
Args
window:str- The name of the window to reload.
screen:str- The name of the screen to reload.
def reloadWindowScreens(self, window: str) ‑> None-
Expand source code
def reloadWindowScreens(self, window: str) -> None: """ Reloads the screens of a window. Args: window (str): The name of the window to reload. """ targetWindow: Window = self.windows.get(window) if targetWindow: targetWindow.reloadScreens()Reloads the screens of a window.
Args
window:str- The name of the window to reload.
def removeScreen(self, name: str) ‑> None-
Expand source code
def removeScreen(self, name: str) -> None: """ Removes a screen from the screens list. Args: name (str): The name of the screen to remove. Raises: Exception: If the screen does not exist. """ if name not in self.screens: raise Exception(f"The screen '{name}' does not exist.") if hasattr(self, 'stackedScreens'): self.stackedScreens.removeWidget(self.screens[name]) self.screens.pop(name)Removes a screen from the screens list.
Args
name:str- The name of the screen to remove.
Raises
Exception- If the screen does not exist.
def removeWindow(self, name: str) ‑> None-
Expand source code
def removeWindow(self, name: str) -> None: """ Removes a window from the windows list. Args: name (str): The name of the window to remove. """ if name in self.windows: del self.windows[name]Removes a window from the windows list.
Args
name:str- The name of the window to remove.
def setScreen(self, name: str, args: dict = None) ‑> None-
Expand source code
def setScreen(self, name: str, args: dict = None) -> None: """ Sets the current screen to display based on the screen name. This method accepts a string name that must match the 'screenName' attribute of a previously added screen. Args: name (str): The name of the screen to display. args (dict): Arguments for the screen. Raises: Exception: If the specified screen does not exist. """ if name in self.screens: currentScreen = self.stackedScreens.currentWidget() if currentScreen: self.screenHistory.append(currentScreen) screen = self.screens[name] if not hasattr(screen, 'screenName'): raise Exception(f'The screen `{screen}` does not have screenName attribute.') if args: INSTANCE_ARGS.setArgs(instance=screen, args=args) self.stackedScreens.setCurrentWidget(screen) else: raise Exception(f'The screen `{name}` does not exist.')Sets the current screen to display based on the screen name.
This method accepts a string name that must match the 'screenName' attribute of a previously added screen.
Args
name:str- The name of the screen to display.
args:dict- Arguments for the screen.
Raises
Exception- If the specified screen does not exist.
def setWindow(self, name: str, args: dict = None) ‑> None-
Expand source code
def setWindow(self, name: str, args: dict = None) -> None: """ Brings a specified window to the front and activates it. Args: name (str): The name of the window to bring to the front. args (dict): Arguments for the window. Raises: Exception: If the specified window does not exist. """ if name in self.windows: self.windows[name].raise_() self.windows[name].activateWindow() if args: INSTANCE_ARGS.setArgs(instance=self.windows[name], args=args) # Execute effect if hasattr(self.windows[name], 'effect'): self.windows[name].effect() else: raise Exception(f"The window '{name}' does not exist.")Brings a specified window to the front and activates it.
Args
name:str- The name of the window to bring to the front.
args:dict- Arguments for the window.
Raises
Exception- If the specified window does not exist.
def setWindowName(self, name: str) ‑> None-
Expand source code
def setWindowName(self, name: str) -> None: """ Changes the name of the window. Args: name (str): The new name for the window. Raises: ValueError: If name is empty or not a string. """ if not name: raise ValueError("Window name must be a non-empty string") self.name = nameChanges the name of the window.
Args
name:str- The new name for the window.
Raises
ValueError- If name is empty or not a string.