Stylesheet Management System¶
Unified stylesheet management with automatic theme translation. Write stylesheets once (light mode), get all themes automatically.
Theme Persistence¶
The StylesheetManager automatically persists the user's theme selection to settings. When the application restarts, the previously selected theme is restored.
from src.shared_services.rendering.stylesheets.api import set_theme, get_theme
# Set theme - automatically saved to settings
set_theme("dark")
# On next app start, the manager loads "dark" from settings
manager = StylesheetManager.instance()
print(manager.get_theme()) # "dark"
The theme is stored in appearance/theme using legacy values (wm/dm) for backward compatibility with the old ViewStyleManager.
To set theme without persisting (useful for previews):
Prerequisites¶
Before using the stylesheet system with PathDef, ensure the path management system is initialized at application startup:
# In main.py or application entry point
from src.shared_services.path_management.api import initialize_paths
def main():
initialize_paths() # Must be called before any PathDef usage
# ... rest of app startup
Quick Start¶
from src.shared_services.rendering.stylesheets.api import (
StylesheetManager,
load_stylesheet,
)
from src.shared_services.path_management.api import get_path_str
# Option 1: Register widget with PathDef stylesheets (recommended)
from mymodule.constants.paths import Stylesheets
manager = StylesheetManager.instance()
manager.register(self, [Stylesheets.MainView, Stylesheets.Components])
# Option 2: Load stylesheet directly using PathDef
css = load_stylesheet(Stylesheets.MainView)
widget.setStyleSheet(css)
# Switch theme - all registered widgets update automatically
manager.set_theme("dark")
Defining Stylesheet Paths with PathDef¶
Define stylesheets using PathDef in your module's constants/paths.py. PathDef paths must be relative to the data root and use valid prefixes.
Valid Path Prefixes¶
| Prefix | PathType | Description |
|---|---|---|
.app_data/ |
REPLACEABLE | Application resources, replaced on updates |
.app_temp/ |
REPLACEABLE | Temporary files |
persistent_data/ |
PROTECTED | User data, preserved across updates |
app_logs/ |
PROTECTED | Log files |
Module-Specific Stylesheet Constants¶
Create a constants/paths.py in your module:
# modules/plant_design/constants/paths.py
from typing import Final
from src.shared_services.path_management.path_types import PathDef, PathType
class Stylesheets:
"""Stylesheet paths for the Plant Design module."""
StartupView: Final = PathDef(
".app_data/stylesheets/PlantDesign/StartUp/startup_view.qss",
PathType.REPLACEABLE,
description="Plant Design startup view stylesheet",
)
ProjectListItem: Final = PathDef(
".app_data/stylesheets/PlantDesign/StartUp/project_list_item.qss",
PathType.REPLACEABLE,
description="Project list item stylesheet",
)
MainView: Final = PathDef(
".app_data/stylesheets/PlantDesign/Main/main_view.qss",
PathType.REPLACEABLE,
description="Main plant design view stylesheet",
)
Shared/Global Stylesheet Constants¶
For stylesheets used across multiple modules, define in:
# src/shared_services/constants/paths.py
from typing import Final
from src.shared_services.path_management.path_types import PathDef, PathType
class Stylesheets:
"""Shared stylesheet paths used across multiple modules."""
Globals: Final = PathDef(
".app_data/stylesheets/globals.qss",
PathType.REPLACEABLE,
description="Global application stylesheet",
)
MessageBoxes: Final = PathDef(
".app_data/stylesheets/MessageBoxes/loading_dialog.qss",
PathType.REPLACEABLE,
description="Loading dialog stylesheet",
)
Stylesheet File Location¶
Stylesheets using PathDef must be placed in the data directory structure:
data/
.app_data/
stylesheets/
globals.qss
PlantDesign/
StartUp/
startup_view.qss
project_list_item.qss
Main/
main_view.qss
SoftwareHub/
home_view.qss
settings_view.qss
MessageBoxes/
loading_dialog.qss
Using the StylesheetManager¶
Registering Widgets¶
from src.shared_services.rendering.stylesheets.api import StylesheetManager
from mymodule.constants.paths import Stylesheets
class MyView(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("MyView")
# Register for automatic theme updates
manager = StylesheetManager.instance()
manager.register(self, [Stylesheets.MainView, Stylesheets.Components])
Loading Stylesheets Directly¶
from src.shared_services.rendering.stylesheets.api import load_stylesheet
from mymodule.constants.paths import Stylesheets
# Load with current theme
css = load_stylesheet(Stylesheets.MainView)
widget.setStyleSheet(css)
# Load with specific theme
dark_css = load_stylesheet(Stylesheets.MainView, theme="dark")
Theme Switching¶
from src.shared_services.rendering.stylesheets.api import set_theme, get_theme
# Switch theme (updates all registered widgets automatically)
set_theme("dark")
# Get current theme
current = get_theme() # "dark"
Theme Change Callbacks¶
def on_theme_change(new_theme: str):
# Handle theme change (update icons, etc.)
pass
manager = StylesheetManager.instance()
manager.on_theme_change(on_theme_change)
Migration from Legacy String Paths¶
The system supports gradual migration from the old ViewStyleManager approach.
New Way (StylesheetManager with PathDef)¶
from src.shared_services.rendering.stylesheets.api import (
StylesheetManager,
load_stylesheet,
)
from modules.plant_design.constants.paths import Stylesheets
manager = StylesheetManager.instance()
manager.register(self, [Stylesheets.StartupView, Stylesheets.ProjectListItem])
css = load_stylesheet(Stylesheets.StartupView)
Migration Steps¶
- Create PathDef constants in your module's
constants/paths.py - Move stylesheet files from
QssHandler/Stylesheets/WM/todata/.app_data/stylesheets/ - Update imports to use PathDef constants
- Replace registration calls from
register_view_styles()toregister()
Temporary Coexistence¶
During migration, both systems can coexist: - Old code using string paths continues to work - New code uses PathDef constants - Both resolve stylesheets and apply theme translation
API Reference¶
StylesheetManager¶
manager = StylesheetManager.instance()
# Register widget with PathDef stylesheets
manager.register(widget, [Stylesheets.MainView, Stylesheets.ListItem])
# Set theme (updates all widgets)
manager.set_theme("dark")
# Get current theme
theme = manager.get_theme()
# Unregister widget
manager.unregister(widget)
# Manual refresh (after modifying stylesheets on disk)
manager.refresh_all()
# Register theme change callback
manager.on_theme_change(callback)
Loading Functions¶
from src.shared_services.rendering.stylesheets.api import (
load_stylesheet,
load_stylesheet_intelligent, # Legacy compatibility
)
# Load with PathDef (recommended)
css = load_stylesheet(Stylesheets.MainView)
# Load with specific theme
css = load_stylesheet(Stylesheets.MainView, theme="dark")
# Legacy: Handle paths with /DM/ or /WM/ markers
css = load_stylesheet_intelligent("QssHandler/Stylesheets/WM/view.qss")
Theme Functions¶
from src.shared_services.rendering.stylesheets.api import set_theme, get_theme
set_theme("dark")
current = get_theme() # "dark"
ThemeTranslator¶
For direct stylesheet translation without file loading:
from src.shared_services.rendering.stylesheets.api import ThemeTranslator
# Translate CSS string from light to dark
dark_css = ThemeTranslator.translate(
light_css,
source_theme="light",
target_theme="dark"
)
# Check if stylesheet uses light theme colors
is_light = ThemeTranslator.is_source_theme(css, "light")
Cache Management¶
from src.shared_services.rendering.stylesheets.api import (
StylesheetCache,
clear_stylesheet_cache,
)
# Check cache size
count = StylesheetCache.size()
# Clear everything
clear_stylesheet_cache()
# Clear specific theme
StylesheetCache.clear_theme("dark")
How It Works¶
PathDef Constant
|
v
get_path_str() --> Absolute file path
|
v
load_stylesheet()
|
+---> StylesheetCache.get(path, theme)
| |
| +--> Cache hit? Return cached
|
+---> Read file from disk
|
+---> ThemeTranslator.translate() (if theme != source)
| |
| +--> ColorSystem mappings
| +--> Hex, rgb(), rgba() conversion
|
+---> Resolve SVG paths
|
+---> StylesheetCache.put(path, theme, result)
|
v
Translated Stylesheet
Key Benefits¶
| Before (Old System) | After (New System) |
|---|---|
| Maintain 2 folders (DM + WM) | Single source folder |
| Manual theme translation | Automatic runtime translation |
| String paths scattered in code | Centralized PathDef constants |
| No path validation | Compile-time path validation |
| Theme sync issues possible | Always in sync |
Stylesheet Writing Guidelines¶
- Write for light mode only - The translator handles dark mode
- Use ColorSystem colors - They translate correctly between themes
- Avoid hardcoded dark colors - Use semantic colors instead
Recommended Colors (Light Mode)¶
| Purpose | Color | ColorSystem Key |
|---|---|---|
| Background | #FFFFFF |
background |
| Surface | #F8FAFC |
surface_1 |
| Text | #0F172A |
text_primary |
| Secondary text | #64748B |
text_secondary |
| Border | #E2E8F0 |
border |
| Primary accent | #2563EB |
primary |
Example Stylesheet¶
/* Write once for light mode */
QWidget {
background-color: #FFFFFF;
color: #0F172A;
}
QPushButton {
background-color: #F8FAFC;
border: 1px solid #E2E8F0;
color: #0F172A;
}
QPushButton:hover {
background-color: #F1F5F9;
}
This automatically becomes:
/* Auto-translated to dark mode */
QWidget {
background-color: #1E1E1E;
color: #D4D4D4;
}
QPushButton {
background-color: #252526;
border: 1px solid #3C3C3C;
color: #D4D4D4;
}
QPushButton:hover {
background-color: #2D2D2D;
}
Files¶
| File | Purpose |
|---|---|
api.py |
Public API exports |
stylesheet_manager.py |
Main manager singleton |
theme_translator.py |
Runtime color translation |
cache.py |
LRU stylesheet cache |
Integration with Icon System¶
The stylesheet system works alongside the icon rendering system:
from src.shared_services.rendering.icons.api import IconColors, render_svg
from src.shared_services.rendering.stylesheets.api import set_theme
# Both use the same ColorSystem
set_theme("dark") # Updates stylesheets AND icon colors
For coordinated theme switching across all rendering systems, use the icon registry's set_theme() which can trigger stylesheet updates via callbacks.
API Reference¶
src.shared_services.rendering.stylesheets.api
¶
Unified Stylesheet System - Public API.
This module provides the public API for the stylesheet management system. Import from here for all stylesheet-related functionality.
USAGE
from src.shared_services.rendering.stylesheets.api import ( StylesheetManager, load_stylesheet, get_stylesheet_manager, ) from mymodule.constants.paths import Stylesheets
Option 1: Register widget with PathDef stylesheets (recommended)¶
manager = StylesheetManager.instance() manager.register(self, [Stylesheets.MainView, Stylesheets.Components])
Option 2: Load stylesheet directly using PathDef¶
css = load_stylesheet(Stylesheets.MainView) widget.setStyleSheet(css)
Switch theme (updates all registered widgets)¶
manager.set_theme("dark")
MIGRATION FROM OLD SYSTEM:
Old way (ViewStyleManager):
from QssHandler.load_qss import ViewStyleManager, get_dynamic_sheet_intelligent
style_manager = ViewStyleManager.instance()
style_manager.register_view_styles(self, ["view.qss"], module_folder="Module")
css = get_dynamic_sheet_intelligent(path)
New way (StylesheetManager):
from src.shared_services.rendering.stylesheets.api import (
StylesheetManager,
load_stylesheet,
)
from mymodule.constants.paths import Stylesheets
manager = StylesheetManager.instance()
manager.register(self, [Stylesheets.MainView]) # Using PathDef
css = load_stylesheet(Stylesheets.MainView)
QUICK REFERENCE:
StylesheetManager.instance()
Get the singleton manager for widget registration.
StylesheetManager.register(widget, stylesheets)
Register a widget with PathDef stylesheets.
StylesheetManager.set_theme(theme)
Switch theme and update all registered widgets.
load_stylesheet(stylesheet, theme)
Load and translate a stylesheet (PathDef or path string).
get_color(key)
Get a QColor from ColorSystem for the active theme.
ThemeTranslator.translate(css, source, target)
Translate stylesheet colors between themes.
StylesheetCache
¶
LRU cache for translated stylesheets.
This cache stores translated stylesheet strings to avoid redundant translations. It uses an OrderedDict for LRU eviction when the cache reaches its maximum size.
The cache is keyed by (stylesheet_path, theme) tuples, allowing the same source stylesheet to be cached for multiple themes simultaneously.
Example
Basic usage::
# Check cache
cached = StylesheetCache.get("/path/to/style.qss", "dark")
if cached is None:
# Translate and cache
translated = translate(source)
StylesheetCache.put("/path/to/style.qss", "dark", translated)
Note
Call StylesheetCache.clear() when switching themes to ensure fresh translations with new color mappings.
Source code in src\shared_services\rendering\stylesheets\cache.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
clear()
classmethod
¶
Clear all cached stylesheets.
Call this when switching themes or when stylesheets may have changed on disk.
clear_theme(theme)
classmethod
¶
Clear cached stylesheets for a specific theme.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
theme
|
str
|
Theme name to clear. |
required |
Source code in src\shared_services\rendering\stylesheets\cache.py
get(path, theme)
classmethod
¶
Get a cached stylesheet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the source stylesheet file. |
required |
theme
|
str
|
Theme name (e.g., "light", "dark"). |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
Cached stylesheet string, or None if not cached. |
Source code in src\shared_services\rendering\stylesheets\cache.py
put(path, theme, stylesheet)
classmethod
¶
Store a translated stylesheet in the cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the source stylesheet file. |
required |
theme
|
str
|
Theme name (e.g., "light", "dark"). |
required |
stylesheet
|
str
|
Translated stylesheet string. |
required |
Source code in src\shared_services\rendering\stylesheets\cache.py
set_max_size(max_size)
classmethod
¶
Set the maximum cache size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_size
|
int
|
Maximum number of stylesheets to cache. |
required |
Source code in src\shared_services\rendering\stylesheets\cache.py
size()
classmethod
¶
Get the current number of cached stylesheets.
Returns:
| Type | Description |
|---|---|
int
|
Number of cached entries. |
StylesheetManager
¶
Manages stylesheet loading and theme translation for widgets.
This singleton class provides: - Widget registration for automatic stylesheet updates - Single-source stylesheet loading (no duplicate DM/WM folders) - Runtime theme translation using ColorSystem - Stylesheet caching for performance - SVG path resolution in QSS files
The manager reads stylesheets from a single source location and translates them on-the-fly based on the current theme. This eliminates the need to maintain parallel DM/WM folder structures.
Example
Basic usage::
manager = StylesheetManager.instance()
# Register widget (in view __init__)
manager.register(
self,
["startup_view.qss", "list_item.qss"],
module="PlantDesign/StartUp"
)
# Later, switch theme
manager.set_theme("dark") # All widgets update automatically
Note
This class is designed as a drop-in replacement for the legacy ViewStyleManager. The API is intentionally similar for easy migration.
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 | |
__init__()
¶
Initialize the stylesheet manager.
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
apply_initial_theme()
¶
Apply the saved theme on application startup.
Call this method after the QApplication is created to apply the palette and global styles. This should be called once during application initialization.
Example::
app = QApplication(sys.argv)
StylesheetManager.instance().apply_initial_theme()
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
cleanup()
¶
Remove references to deleted widgets.
Called automatically during updates, but can be called manually to free memory.
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
configure(stylesheet_base=None, source_theme=None, project_root=None)
¶
Configure the stylesheet manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stylesheet_base
|
Optional[str]
|
Base directory for source stylesheets. |
None
|
source_theme
|
Optional[str]
|
Theme of the source stylesheets. |
None
|
project_root
|
Optional[Union[str, Path]]
|
Project root directory for path resolution. |
None
|
Example::
manager.configure(
stylesheet_base="src/stylesheets",
source_theme="light",
project_root="/path/to/project"
)
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
get_project_root()
¶
Get the project root directory.
Returns:
| Type | Description |
|---|---|
Path
|
Path to the project root. |
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
get_registered_count()
¶
Get the number of registered widgets.
Returns:
| Type | Description |
|---|---|
int
|
Number of registered entries. |
get_theme()
¶
instance()
classmethod
¶
Get the singleton instance.
Returns:
| Type | Description |
|---|---|
StylesheetManager
|
The shared StylesheetManager instance. |
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
load_stylesheet(stylesheet, theme=None)
¶
Load and translate a stylesheet.
This is the main function for loading stylesheets. It: 1. Resolves PathDef or path string to absolute path 2. Reads the source stylesheet file 3. Translates colors if needed for the target theme 4. Resolves SVG paths in the stylesheet 5. Caches the result
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stylesheet
|
StylesheetSpec
|
PathDef object or path string to the stylesheet. |
required |
theme
|
Optional[str]
|
Target theme (default: current theme). |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Translated stylesheet string. |
Example
Using PathDef::
from mymodule.constants.paths import Stylesheets
css = manager.load_stylesheet(Stylesheets.MainView)
Using string path::
css = manager.load_stylesheet("views/main.qss")
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
on_theme_change(callback)
¶
Register a callback for theme changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callback
|
Callable[[str], None]
|
Function to call with new theme name. |
required |
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
refresh_all()
¶
Refresh all registered widgets.
Call this after modifying stylesheets on disk.
refresh_widget(widget)
¶
Refresh stylesheet for a specific widget.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
widget
|
QWidget
|
Widget to refresh. |
required |
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
register(widget, stylesheets, module=None)
¶
Register a widget for stylesheet management.
The widget will have its stylesheet applied immediately and will be automatically updated when the theme changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
widget
|
QWidget
|
The Qt widget to style. |
required |
stylesheets
|
List[StylesheetSpec]
|
List of PathDef objects or path strings. |
required |
module
|
Optional[str]
|
Optional module subdirectory (legacy support for string paths). |
None
|
Example
Using PathDef (recommended)::
from mymodule.constants.paths import Stylesheets
manager.register(self, [Stylesheets.MainView, Stylesheets.ListItem])
Using string paths (legacy)::
manager.register(
self,
["startup_view.qss", "list_item.qss"],
module="PlantDesign/StartUp"
)
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
reset_instance()
classmethod
¶
Reset the singleton instance.
Useful for testing or reinitializing the manager.
set_theme(theme, persist=True)
¶
Switch theme and update all registered widgets.
This method performs a complete theme switch: 1. Updates the QPalette for native Qt widgets and Windows frame 2. Clears stylesheet cache and re-applies all stylesheets 3. Applies global context menu styles 4. Syncs the icon system 5. Refreshes special widgets (QListWidget, QTextBrowser)
The theme selection is persisted to settings by default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
theme
|
str
|
Theme name ("light" or "dark"). |
required |
persist
|
bool
|
If True, save the theme to settings for persistence across application restarts. |
True
|
Example::
manager.set_theme("dark")
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
unregister(widget)
¶
Unregister a widget from stylesheet management.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
widget
|
QWidget
|
The widget to unregister. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the widget was found and unregistered. |
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
ThemeTranslator
¶
Runtime theme translator for QSS stylesheets.
Translates colors in stylesheet text from one theme to another using the centralized ColorSystem. Supports hex colors, rgb(), and rgba() formats.
The translator uses intelligent color mapping to convert semantic colors (backgrounds, text, surfaces) appropriately between themes while preserving the stylesheet structure.
Example
Basic usage::
# Light to dark translation
dark_css = ThemeTranslator.translate(
light_css,
source_theme="light",
target_theme="dark"
)
# Check if translation needed
if not ThemeTranslator.is_source_theme(css, "light"):
# Already translated or unknown source
pass
Note
For best results, source stylesheets should use colors from the ColorSystem light theme palette.
Source code in src\shared_services\rendering\stylesheets\theme_translator.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 | |
clear_mapping_cache()
classmethod
¶
Clear the color mapping cache.
Call this if ColorSystem colors are modified at runtime.
get_available_themes()
classmethod
¶
Get list of available themes.
Returns:
| Type | Description |
|---|---|
List[str]
|
List of theme names that can be used for translation. |
Source code in src\shared_services\rendering\stylesheets\theme_translator.py
is_source_theme(stylesheet, expected_source='light')
classmethod
¶
Check if a stylesheet appears to be in the expected source theme.
This is a heuristic check based on common colors. Use it to determine if translation is needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stylesheet
|
str
|
Stylesheet text to check. |
required |
expected_source
|
str
|
Expected source theme. |
'light'
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the stylesheet appears to be in the source theme. |
Source code in src\shared_services\rendering\stylesheets\theme_translator.py
translate(stylesheet, source_theme='light', target_theme='dark')
classmethod
¶
Translate a stylesheet from source theme to target theme.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stylesheet
|
str
|
QSS stylesheet text to translate. |
required |
source_theme
|
str
|
Source theme name (default: "light"). |
'light'
|
target_theme
|
str
|
Target theme name (default: "dark"). |
'dark'
|
Returns:
| Type | Description |
|---|---|
str
|
Translated stylesheet text. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If source and target themes are the same. |
Example::
light_css = "background: #FFFFFF; color: #0F172A;"
dark_css = ThemeTranslator.translate(light_css)
# dark_css now has dark theme colors
Source code in src\shared_services\rendering\stylesheets\theme_translator.py
apply_initial_theme()
¶
Apply the saved theme on application startup.
Call this after the QApplication is created to apply the palette and global styles for the saved theme.
Example::
app = QApplication(sys.argv)
apply_initial_theme() # Apply palette and context menu styles
Source code in src\shared_services\rendering\stylesheets\api.py
clear_stylesheet_cache()
¶
Clear the stylesheet cache.
Call this if stylesheets have been modified on disk if you want to reload them.
get_color(key, theme=None)
¶
Get a QColor from the ColorSystem for the current (or specified) theme.
This gives custom paint code access to the same semantic color tokens that QSS stylesheets use, so delegates and other owner-draw code stay consistent with the application theme.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Color token name (e.g. |
required |
theme
|
Optional[str]
|
Optional theme override. Defaults to the current theme. |
None
|
Returns:
| Type | Description |
|---|---|
QColor
|
QColor for the requested token. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If key is not found in the color palette. |
Example::
from src.shared_services.rendering.stylesheets.api import get_color
hover_bg = get_color("surface_2")
painter.fillRect(rect, hover_bg)
Source code in src\shared_services\rendering\stylesheets\api.py
get_stylesheet_manager()
¶
Convenience function to get the StylesheetManager singleton.
Returns:
| Type | Description |
|---|---|
StylesheetManager
|
The shared StylesheetManager instance. |
Example::
manager = get_stylesheet_manager()
manager.register(widget, ["style.qss"])
Source code in src\shared_services\rendering\stylesheets\stylesheet_manager.py
get_theme()
¶
Get the current theme.
Returns:
| Type | Description |
|---|---|
str
|
Current theme name. |
load_stylesheet(stylesheet, theme=None)
¶
Load and translate a stylesheet file.
This is a convenience function that loads a stylesheet and translates it to the specified (or current) theme.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stylesheet
|
StylesheetSpec
|
PathDef object or path string to the stylesheet. |
required |
theme
|
Optional[str]
|
Target theme (default: current theme from manager). |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Translated stylesheet string ready to apply. |
Example
Using PathDef (recommended)::
from mymodule.constants.paths import Stylesheets
css = load_stylesheet(Stylesheets.MainView)
widget.setStyleSheet(css)
Using string path::
css = load_stylesheet("views/main_view.qss")
Force specific theme::
dark_css = load_stylesheet(Stylesheets.MainView, theme="dark")
Source code in src\shared_services\rendering\stylesheets\api.py
load_stylesheet_intelligent(path)
¶
Load a stylesheet with intelligent path handling.
This function is a drop-in replacement for get_dynamic_sheet_intelligent. It handles paths that may contain /DM/ or /WM/ markers and loads from the appropriate source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
Path to the stylesheet (may contain /DM/ or /WM/). |
required |
Returns:
| Type | Description |
|---|---|
str
|
Translated stylesheet string for current theme. |
Example::
# These all work the same:
css = load_stylesheet_intelligent("QssHandler/Stylesheets/WM/view.qss")
css = load_stylesheet_intelligent("QssHandler/Stylesheets/DM/view.qss")
css = load_stylesheet_intelligent("view.qss")
Source code in src\shared_services\rendering\stylesheets\api.py
set_theme(theme)
¶
Set the application theme.
This updates the StylesheetManager theme and refreshes all registered widgets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
theme
|
str
|
Theme name ("light" or "dark"). |
required |
Example::
set_theme("dark") # All registered widgets update