qss_parser.qss_parser module

class qss_parser.qss_parser.BaseQSSPlugin(error_handler: ErrorHandlerProtocol)[source]

Bases: QSSParserPlugin

Base implementation of QSSParserPlugin.

This class provides common functionality for QSS parser plugins, including error handling and property line processing.

_error_handler

Handler for reporting errors.

Type:

ErrorHandlerProtocol

_logger

Logger instance for debugging and error reporting.

Type:

logging.Logger

__init__(error_handler: ErrorHandlerProtocol) None[source]

Initialize a new BaseQSSPlugin instance.

Parameters:

error_handler (ErrorHandlerProtocol) – Handler for reporting errors.

class qss_parser.qss_parser.Constants[source]

Bases: object

A class containing constant values and patterns used throughout the QSS parser.

This class defines regular expression patterns and lists of valid pseudo-elements and pseudo-states used in Qt Style Sheets (QSS).

ATTRIBUTE_PATTERN

Regular expression pattern for matching QSS attribute selectors.

Type:

str

COMPILED_ATTRIBUTE_PATTERN

Compiled version of ATTRIBUTE_PATTERN for better performance.

Type:

Pattern[str]

VARIABLE_PATTERN

Regular expression pattern for matching QSS variable declarations.

Type:

str

COMPLETE_RULE_PATTERN

Regular expression pattern for matching complete QSS rules.

Type:

str

PSEUDO_PATTERN

Regular expression pattern for matching pseudo-elements and pseudo-states.

Type:

str

CLASS_ID_PATTERN

Regular expression pattern for matching class and ID combinations.

Type:

str

COMBINATOR_PATTERN

Regular expression pattern for matching QSS combinators.

Type:

str

PSEUDO_ELEMENTS

List of valid QSS pseudo-elements.

Type:

List[str]

PSEUDO_STATES

List of valid QSS pseudo-states.

Type:

List[str]

class qss_parser.qss_parser.DefaultPropertyProcessor(error_handler: ErrorHandlerProtocol)[source]

Bases: object

Default implementation of the PropertyProcessorProtocol.

This class handles the processing of QSS property declarations, including validation and variable resolution.

_error_handler

Handler for reporting errors.

Type:

ErrorHandlerProtocol

_logger

Logger instance for debugging and error reporting.

Type:

logging.Logger

__init__(error_handler: ErrorHandlerProtocol) None[source]

Initialize a new DefaultPropertyProcessor instance.

Parameters:

error_handler (ErrorHandlerProtocol) – Handler for reporting errors.

process_property(line: str, rules: List[QSSRule], variable_manager: VariableManager, line_num: int) None[source]

Process a QSS property line and add it to the rules.

This method validates the property syntax, resolves any variables, and adds the property to all applicable rules.

Parameters:
  • line (str) – The property line to process.

  • rules (List[QSSRule]) – List of rules to add the property to.

  • variable_manager (VariableManager) – Manager for resolving variables.

  • line_num (int) – The line number for error reporting.

class qss_parser.qss_parser.ErrorHandlerProtocol(*args, **kwargs)[source]

Bases: Protocol

Protocol defining the interface for error handlers.

This protocol defines how parsing errors should be handled and dispatched during QSS processing.

__init__(*args, **kwargs)
class qss_parser.qss_parser.MetaObjectProtocol(*args, **kwargs)[source]

Bases: Protocol

Protocol defining the interface for Qt meta objects.

This protocol represents the minimal interface required for accessing Qt meta object information, specifically the class name.

__init__(*args, **kwargs)
class qss_parser.qss_parser.ParserEvent(*values)[source]

Bases: Enum

Enumeration of events that can occur during QSS parsing.

These events can be subscribed to using the QSSParser.on() method.

class qss_parser.qss_parser.ParserState(rules: ~typing.List[~qss_parser.qss_parser.QSSRule] = <factory>, buffer: str = '', in_comment: bool = False, in_rule: bool = False, in_variables: bool = False, current_selectors: ~typing.List[str] = <factory>, original_selector: str | None = None, current_rules: ~typing.List[~qss_parser.qss_parser.QSSRule] = <factory>, variable_buffer: str = '', current_line: int = 1, property_lines: ~typing.List[str] = <factory>, rule_start_line: int = 0)[source]

Bases: object

A dataclass representing the state of the QSS parser.

This class maintains the current state of the parser, including rules being processed, buffers, flags, and line tracking information.

rules

List of all parsed QSS rules.

Type:

List[QSSRule]

buffer

Buffer for accumulating partial property declarations.

Type:

str

in_comment

Flag indicating if currently parsing a comment.

Type:

bool

in_rule

Flag indicating if currently parsing a rule.

Type:

bool

in_variables

Flag indicating if currently parsing variables.

Type:

bool

current_selectors

List of selectors being processed.

Type:

List[str]

original_selector

Original selector text before processing.

Type:

Optional[str]

current_rules

List of rules currently being processed.

Type:

List[QSSRule]

variable_buffer

Buffer for accumulating variable declarations.

Type:

str

current_line

Current line number being processed.

Type:

int

property_lines

List of property lines in current rule.

Type:

List[str]

rule_start_line

Line number where current rule started.

Type:

int

__init__(rules: ~typing.List[~qss_parser.qss_parser.QSSRule] = <factory>, buffer: str = '', in_comment: bool = False, in_rule: bool = False, in_variables: bool = False, current_selectors: ~typing.List[str] = <factory>, original_selector: str | None = None, current_rules: ~typing.List[~qss_parser.qss_parser.QSSRule] = <factory>, variable_buffer: str = '', current_line: int = 1, property_lines: ~typing.List[str] = <factory>, rule_start_line: int = 0) None
reset() None[source]

Reset the parser state to its initial values.

This method clears all buffers and resets all flags and counters to their default values.

class qss_parser.qss_parser.PropertyPlugin(property_processor: PropertyProcessorProtocol, error_handler: ErrorHandlerProtocol)[source]

Bases: BaseQSSPlugin

Plugin for handling QSS property declarations.

This plugin processes property declarations within rule blocks, delegating the actual property processing to a property processor.

_property_processor

Processor for handling properties.

Type:

PropertyProcessorProtocol

_error_handler

Handler for reporting errors.

Type:

ErrorHandlerProtocol

__init__(property_processor: PropertyProcessorProtocol, error_handler: ErrorHandlerProtocol) None[source]

Initialize a new PropertyPlugin instance.

Parameters:
process_line(line: str, state: ParserState, variable_manager: VariableManager) bool[source]

Process a line containing QSS property declarations.

This method handles property lines within rule blocks, adding them to the current rule’s property list.

Parameters:
  • line (str) – The line to process.

  • state (ParserState) – Current state of the parser.

  • variable_manager (VariableManager) – Manager for handling variables.

Returns:

True if the line was processed as a property, False otherwise.

Return type:

bool

class qss_parser.qss_parser.PropertyProcessorProtocol(*args, **kwargs)[source]

Bases: Protocol

Protocol defining the interface for QSS property processors.

This protocol defines how property lines in QSS should be processed and added to rules.

__init__(*args, **kwargs)
class qss_parser.qss_parser.QSSFormatter[source]

Bases: object

A utility class for formatting QSS rules.

This class provides static methods for converting QSS rules into properly formatted strings suitable for output or display.

static format_rule(selector: str, properties: List[QSSProperty]) str[source]

Format a QSS rule with its selector and properties.

This method normalizes the selector and formats the properties with proper indentation and line breaks.

Parameters:
  • selector (str) – The selector for the rule.

  • properties (List[QSSProperty]) – List of properties to format.

Returns:

The formatted QSS rule as a string.

Return type:

str

class qss_parser.qss_parser.QSSParser(property_processor: PropertyProcessorProtocol | None = None, plugins: List[QSSParserPlugin] | None = None, logger: Logger | None = None)[source]

Bases: object

Main class for parsing Qt Style Sheets (QSS).

This class coordinates the parsing of QSS content using a plugin-based architecture, managing the overall parsing process and maintaining the state of parsed rules.

_state

Current state of the parser.

Type:

ParserState

_style_selector

Selector for applying styles to widgets.

Type:

QSSStyleSelector

_variable_manager

Manager for handling variables.

Type:

VariableManager

_event_handlers

Event handlers.

Type:

Dict[str, List[Callable[…, None]]]

_rule_map

Map of selectors to rules.

Type:

Dict[str, QSSRule]

_logger

Logger instance for debugging and error reporting.

Type:

logging.Logger

_error_handler

Handler for reporting errors.

Type:

ErrorHandlerProtocol

_property_processor

Processor for properties.

Type:

PropertyProcessorProtocol

_plugins

List of parser plugins.

Type:

List[QSSParserPlugin]

__init__(property_processor: PropertyProcessorProtocol | None = None, plugins: List[QSSParserPlugin] | None = None, logger: Logger | None = None) None[source]

Initialize a new QSSParser instance.

Parameters:
  • property_processor (Optional[PropertyProcessorProtocol]) – Custom property processor. If None, uses DefaultPropertyProcessor.

  • plugins (Optional[List[QSSParserPlugin]]) – List of parser plugins. If None, uses default plugins.

  • logger (Optional[logging.Logger]) – Custom logger instance.

dispatch_error(error: str) None[source]

Dispatch an error message to all error handlers.

Parameters:

error (str) – The error message to dispatch.

get_styles_for(widget: WidgetProtocol, fallback_class: str | None = None, additional_selectors: List[str] | None = None, include_class_if_object_name: bool = False) str[source]

Get the styles that apply to a widget.

Parameters:
  • widget (WidgetProtocol) – The widget to get styles for.

  • fallback_class (Optional[str]) – Fallback class name if no styles match.

  • additional_selectors (Optional[List[str]]) – Additional selectors to include.

  • include_class_if_object_name (bool) – Whether to include class styles when object name is present.

Returns:

The combined styles that apply to the widget.

Return type:

str

handle_rule(rule: QSSRule) None[source]

Handle a newly parsed QSS rule.

This method merges or adds the rule to the parser’s rule collection and notifies rule handlers.

Parameters:

rule (QSSRule) – The rule to handle.

on(event: ParserEvent, handler: Callable[[...], None]) None[source]

Register a handler for a parser event.

Parameters:
  • event (ParserEvent) – The event to handle.

  • handler (Callable[..., None]) – The handler function.

parse(qss_text: str) None[source]

Parse a QSS text string.

This method processes the QSS text line by line using the registered plugins.

Parameters:

qss_text (str) – The QSS text to parse.

to_string() str[source]

Convert all parsed rules to a formatted string.

Returns:

The formatted QSS string.

Return type:

str

class qss_parser.qss_parser.QSSParserPlugin[source]

Bases: ABC

Abstract base class for QSS parser plugins.

This class defines the interface that all parser plugins must implement to process QSS content.

abstractmethod process_line(line: str, state: ParserState, variable_manager: VariableManager) bool[source]

Process a single line of QSS content.

Parameters:
  • line (str) – The line to process.

  • state (ParserState) – Current state of the parser.

  • variable_manager (VariableManager) – Manager for handling variables.

Returns:

True if the line was processed by this plugin, False otherwise.

Return type:

bool

class qss_parser.qss_parser.QSSProperty(name: str, value: str)[source]

Bases: object

A dataclass representing a QSS property with its name and value.

This class handles the storage and formatting of individual QSS properties, ensuring proper string formatting and dictionary conversion.

name

The name of the QSS property.

Type:

str

value

The value of the QSS property.

Type:

str

__init__(name: str, value: str) None
to_dict() QSSPropertyDict[source]

Converts the property to a dictionary format.

Returns:

A dictionary containing the property name and value.

Return type:

QSSPropertyDict

class qss_parser.qss_parser.QSSPropertyDict[source]

Bases: TypedDict

TypedDict defining the structure of a QSS property dictionary.

name

The name of the QSS property.

Type:

str

value

The value of the QSS property.

Type:

str

class qss_parser.qss_parser.QSSRule(selector: str)[source]

Bases: object

A class representing a QSS rule with its selector and properties.

This class handles the parsing and storage of QSS rules, including selector parsing and property management.

selector

The CSS selector for this rule.

Type:

str

properties

List of properties associated with this rule.

Type:

List[QSSProperty]

object_name

The object name extracted from the selector.

Type:

Optional[str]

class_name

The class name extracted from the selector.

Type:

Optional[str]

attributes

List of attributes extracted from the selector.

Type:

List[str]

pseudo_states

List of pseudo-states extracted from the selector.

Type:

List[str]

__init__(selector: str) None[source]

Initialize a QSS rule with the given selector.

Parameters:

selector (str) – The CSS selector for this rule.

add_property(name: str, value: str) None[source]

Add a new property to the rule.

Parameters:
  • name (str) – The name of the property.

  • value (str) – The value of the property.

clone_without_pseudo_elements() QSSRule[source]

Create a copy of this rule without pseudo-elements.

Returns:

A new rule with the same properties but without pseudo-elements

in the selector.

Return type:

QSSRule

class qss_parser.qss_parser.QSSStyleSelector(logger: Logger | None = None)[source]

Bases: object

Class for selecting and applying QSS styles to widgets.

This class handles the matching of QSS rules to widgets based on their class names, object names, and other selectors.

_logger

Logger instance for debugging and error reporting.

Type:

logging.Logger

__init__(logger: Logger | None = None) None[source]

Initialize a new QSSStyleSelector instance.

Parameters:

logger (Optional[logging.Logger]) – Custom logger instance.

get_styles_for(rules: List[QSSRule], widget: WidgetProtocol, fallback_class: str | None = None, additional_selectors: List[str] | None = None, include_class_if_object_name: bool = False) str[source]

Get all styles that apply to a widget.

This method matches rules against the widget based on its class name, object name, and additional selectors.

Parameters:
  • rules (List[QSSRule]) – List of all available rules.

  • widget (WidgetProtocol) – The widget to get styles for.

  • fallback_class (Optional[str]) – Fallback class name if no styles match.

  • additional_selectors (Optional[List[str]]) – Additional selectors to include.

  • include_class_if_object_name (bool) – Whether to include class styles when object name is present.

Returns:

The combined styles that apply to the widget.

Return type:

str

class qss_parser.qss_parser.RuleHandlerProtocol(*args, **kwargs)[source]

Bases: Protocol

Protocol defining the interface for QSS rule handlers.

This protocol defines how QSS rules should be handled after they are parsed and validated.

__init__(*args, **kwargs)
class qss_parser.qss_parser.SelectorPlugin(property_processor: PropertyProcessorProtocol, rule_handler: RuleHandlerProtocol, error_handler: ErrorHandlerProtocol)[source]

Bases: BaseQSSPlugin

Plugin for handling QSS selectors and rules.

This plugin processes selector declarations and manages rule creation, including handling of complete rules, rule start/end, and property processing.

_property_processor

Processor for handling properties.

Type:

PropertyProcessorProtocol

_rule_handler

Handler for managing rules.

Type:

RuleHandlerProtocol

_error_handler

Handler for reporting errors.

Type:

ErrorHandlerProtocol

__init__(property_processor: PropertyProcessorProtocol, rule_handler: RuleHandlerProtocol, error_handler: ErrorHandlerProtocol) None[source]

Initialize a new SelectorPlugin instance.

Parameters:
process_line(line: str, state: ParserState, variable_manager: VariableManager) bool[source]

Process a line of QSS content, handling selectors and rules.

This method handles complete rules, selector parts, and rule boundaries.

Parameters:
  • line (str) – The line to process.

  • state (ParserState) – Current state of the parser.

  • variable_manager (VariableManager) – Manager for handling variables.

Returns:

True if the line was processed by this plugin, False otherwise.

Return type:

bool

class qss_parser.qss_parser.SelectorUtils[source]

Bases: object

A utility class for handling QSS selectors.

This class provides static methods for parsing, validating, and manipulating QSS selectors, including handling of attributes, pseudo-states, and selector normalization.

static extract_attributes(selector: str) List[str][source]

Extract attribute selectors from a QSS selector.

Parameters:

selector (str) – The selector to extract attributes from.

Returns:

List of attribute selectors found in the selector.

Return type:

List[str]

static is_complete_rule(line: str) bool[source]

Check if a line contains a complete QSS rule.

Parameters:

line (str) – The line to check.

Returns:

True if the line contains a complete rule, False otherwise.

Return type:

bool

static normalize_selector(selector: str) str[source]

Normalize a QSS selector by standardizing spacing and formatting.

This method handles attribute selectors, class-id combinations, and combinator spacing.

Parameters:

selector (str) – The selector to normalize.

Returns:

The normalized selector string.

Return type:

str

static parse_selector(selector: str) Tuple[str | None, str | None, List[str], List[str]][source]

Parse a QSS selector into its components.

Parameters:

selector (str) – The selector to parse.

Returns:

A tuple containing:
  • object_name: The object name if present, None otherwise

  • class_name: The class name if present, None otherwise

  • attributes: List of attribute selectors

  • pseudo_states: List of pseudo-states

Return type:

Tuple[Optional[str], Optional[str], List[str], List[str]]

static strip_comments(line: str) str[source]

Remove inline and block comments from a QSS line.

Parameters:

line (str) – The input line to process.

Returns:

The line with comments removed.

Return type:

str

static validate_selector_syntax(selector: str, line_num: int) List[str][source]

Validate the syntax of a QSS selector.

This method checks for various syntax errors including: - Duplicate selectors in comma-separated lists - Invalid pseudo-states - Malformed attribute selectors - Invalid spacing - Invalid combinators

Parameters:
  • selector (str) – The selector to validate.

  • line_num (int) – The line number for error reporting.

Returns:

List of error messages for any syntax errors found.

Return type:

List[str]

class qss_parser.qss_parser.VariableManager[source]

Bases: object

A class for managing QSS variables and their values.

This class handles the parsing, storage, and resolution of QSS variables, including handling of circular references and undefined variables.

_variables

Dictionary storing variable names and their values.

Type:

dict

_logger

Logger instance for debugging and error reporting.

Type:

logging.Logger

__init__() None[source]

Initialize a new VariableManager instance.

parse_variables(block: str, start_line: int = 1, on_variable_defined: Callable[[str, str], None] | None = None) List[str][source]

Parse a block of variable declarations.

Parameters:
  • block (str) – The text block containing variable declarations.

  • start_line (int, optional) – The starting line number for error reporting. Defaults to 1.

  • on_variable_defined (Optional[Callable[[str, str], None]], optional) – Callback function called when a variable is defined. Defaults to None.

Returns:

List of error messages encountered during parsing.

Return type:

List[str]

resolve_variable(value: str) Tuple[str, str | None][source]

Resolve variable references in a value string.

This method handles nested variable references and detects circular references.

Parameters:

value (str) – The value string that may contain variable references.

Returns:

A tuple containing:
  • The resolved value string

  • An error message if any errors occurred, None otherwise

Return type:

Tuple[str, Optional[str]]

class qss_parser.qss_parser.VariablePlugin(error_handler: ErrorHandlerProtocol)[source]

Bases: QSSParserPlugin

Plugin for handling QSS variable declarations.

This plugin processes variable declarations within @variables blocks, managing the parsing and validation of variable definitions.

_error_handler

Handler for reporting errors.

Type:

ErrorHandlerProtocol

_logger

Logger instance for debugging and error reporting.

Type:

logging.Logger

__init__(error_handler: ErrorHandlerProtocol) None[source]

Initialize a new VariablePlugin instance.

Parameters:

error_handler (ErrorHandlerProtocol) – Handler for reporting errors.

process_line(line: str, state: ParserState, variable_manager: VariableManager) bool[source]

Process a line that may contain variable declarations.

This method handles the start and end of variable blocks, as well as the variable declarations within them.

Parameters:
  • line (str) – The line to process.

  • state (ParserState) – Current state of the parser.

  • variable_manager (VariableManager) – Manager for handling variables.

Returns:

True if the line was processed as part of variable handling,

False otherwise.

Return type:

bool

class qss_parser.qss_parser.WidgetProtocol(*args, **kwargs)[source]

Bases: Protocol

Protocol defining the interface for Qt widgets.

This protocol represents the minimal interface required for accessing Qt widget information, including object name and meta object data.

__init__(*args, **kwargs)