Skip to content

WebEnginePage

Qt Base Class: QWebEnginePage

Signature: QWebEnginePage(self, parent: Optional[PySide6.QtCore.QObject] = None) -> None QWebEnginePage(self, profile: PySide6.QtWebEngineCore.QWebEngineProfile, parent: Optional[PySide6.QtCore.QObject] = None) -> None

Base classes

Name Children Inherits
ObjectMixin
prettyqt.core.object
QWebEnginePage
PySide6.QtWebEngineCore
QWebEnginePage(self, parent: Optional[PySide6.QtCore.QObject] \= None) -> None

⋔ Inheritance diagram

graph TD
  1473574738592["webenginecore.WebEnginePage"]
  1473299815024["core.ObjectMixin"]
  140713234304496["builtins.object"]
  1473574700528["QtWebEngineCore.QWebEnginePage"]
  1473288842240["QtCore.QObject"]
  1473291690208["Shiboken.Object"]
  1473299815024 --> 1473574738592
  140713234304496 --> 1473299815024
  1473574700528 --> 1473574738592
  1473288842240 --> 1473574700528
  1473291690208 --> 1473288842240
  140713234304496 --> 1473291690208

🛈 DocStrings

Bases: ObjectMixin, QWebEnginePage

A web engine page holds the HTML document contents, link history + actions.

Source code in prettyqt\webenginecore\webenginepage.py
class WebEnginePage(core.ObjectMixin, webenginecore.QWebEnginePage):
    """A web engine page holds the HTML document contents, link history + actions."""

    def get_icon(self) -> gui.Icon | None:
        """Return icon. If icon is Null, return None."""
        icon = self.icon()
        return None if icon.isNull() else gui.Icon(icon)

    def set_url(self, url: datatypes.PathType | datatypes.UrlType):
        """Set the url of the WebEnginePage.

        Clears the Page and loads the URL.

        Args:
            url: URL to set
        """
        self.setUrl(datatypes.to_url(url))

    def get_url(self) -> core.Url:
        return core.Url(self.url())

    def get_icon_url(self) -> core.Url:
        return core.Url(self.iconUrl())

    def get_requested_url(self) -> core.Url:
        return core.Url(self.requestedUrl())

    def get_scroll_position(self) -> core.PointF:
        return core.PointF(self.scrollPosition())

    def get_contents_size(self) -> core.SizeF:
        return core.SizeF(self.contentsSize())

    def load_url(self, url: datatypes.UrlType | datatypes.PathType):
        """Load the URL.

        Loads the specified url and displays it.

        Note: The Page remains the same until enough data has arrived
        to display the new URL.

        Args:
            url: URL to load
        """
        self.load(datatypes.to_url(url))

    def set_zoom(self, zoom: float):
        """Set the zoom factor for the Page.

        Valid values are within the range from 0.25 to 5.0. The default factor is 1.0.

        Args:
            zoom: Zoom factor
        """
        self.setZoomFactor(zoom)

    def find_text(
        self,
        string: str,
        backward: bool = False,
        case_sensitive: bool = False,
        callback: Callable[[bool], None] | None = None,
    ):
        """Find text in the current page.

        Finds the specified string, subString, in the page, using the given options.
        The findTextFinished() signal is emitted when a string search is completed.

        To clear the search highlight, just pass an empty string.

        The resultCallback must take a boolean parameter.
        It will be called with a value of true if the subString was found;
        otherwise the callback value will be false.

        Warning: It is guaranteed that the callback is always called,
        but it might be done during page destruction. When WebEnginePage is deleted,
        the callback is triggered with an invalid value and it is not safe to use
        the corresponding QWebEnginePage or QWebEnginePage instance inside it.

        Args:
            string: string to search for
            backward: search backwards
            case_sensitive: case-sensitive search
            callback: result callback
        """
        if callback is None:

            def do_nothing(x):
                pass

            callback = do_nothing
        flag = webenginecore.QWebEnginePage.FindFlag(0)
        if case_sensitive:
            flag |= self.FindFlag.FindCaseSensitively
        if backward:
            flag |= self.FindFlag.FindBackward
        self.findText(string, flag, callback)

    def set_lifecycle_state(self, state: LifecycleStateStr | mod.LifecycleState):
        """Set lifecycle state.

        Args:
            state: lifecycle state
        """
        self.setLifecycleState(LIFECYCLE_STATE.get_enum_value(state))

    def get_lifecycle_state(self) -> LifecycleStateStr:
        """Get the current lifecycle state.

        Returns:
            lifecycle state
        """
        return LIFECYCLE_STATE.inverse[self.lifecycleState()]

    def trigger_action(self, action: WebActionStr | mod.WebAction, checked: bool = False):
        """Trigger action."""
        self.triggerAction(WEB_ACTION.get_enum_value(action), checked)

    def set_feature_permission(
        self,
        url: datatypes.UrlType,
        feature: FeatureStr | mod.Feature,
        policy: PermissionPolicyStr | mod.PermissionPolicy,
    ):
        """Set permission of feature for given URL."""
        url = core.Url(url)
        self.setFeaturePermission(
            url, FEATURE.get_enum_value(feature), PERMISSION_POLICY.get_enum_value(policy)
        )

    def get_history(self) -> webenginecore.WebEngineHistory:
        hist = self.history()
        return webenginecore.WebEngineHistory(hist)

    def get_settings(self) -> webenginecore.WebEngineSettings:
        """Get WebEngineSettings (a MutableMapping)."""
        settings = self.settings()
        return webenginecore.WebEngineSettings(settings)

    def set_setting(
        self,
        setting_name: webenginecore.webenginesettings.WebAttributeStr,
        value: bool,
    ):
        """Set WebEngine setting to value."""
        self.get_settings()[setting_name] = value

    def get_setting(
        self,
        setting_name: webenginecore.webenginesettings.WebAttributeStr,
    ) -> bool:
        """Return value of given WebEngine setting."""
        return self.get_settings()[setting_name]

    def get_scripts(self) -> webenginecore.WebEngineScriptCollection:
        """Get script collection."""
        return webenginecore.WebEngineScriptCollection(self.scripts())

    def open_in_browser(self):
        """Open page URL in default system browser."""
        try:
            webbrowser.open(self.getUrl().toString())
        except ValueError as e:
            logger.exception(e)

    def insert_stylesheet(
        self, name: str, css: str | os.PathLike, immediately: bool = True
    ):
        """Load css using JavaScript.

        Arguments:
            name: CSS id
            css: CSS stylesheet, either a string or a PathLike object.
            immediately: whther to run javascript immediately
        """
        if isinstance(css, os.PathLike):
            path = core.File(os.fspath(css))
            if not path.open(
                core.File.OpenModeFlag.ReadOnly | core.File.OpenModeFlag.Text
            ):
                return
            css = path.readAll().data().decode("utf-8")
        script = webenginecore.WebEngineScript()
        s = """
        (function() {
        css = document.createElement('style');
        css.type = 'text/css';
        css.id = "%s";
        document.head.appendChild(css);
        css.innerText = `%s`;
        })()
        """
        s = s % (name, css)
        script = webenginecore.WebEngineScript()
        if immediately:
            self.runJavaScript(s, script.ScriptWorldId.ApplicationWorld)
        script.setName(name)
        script.setSourceCode(s)
        script.setInjectionPoint(script.InjectionPoint.DocumentReady)
        script.setRunsOnSubFrames(True)
        script.setWorldId(script.ScriptWorldId.ApplicationWorld)
        self.scripts().insert(script)

    def mousedown(self, selector: str, btn: Literal["left", "middle", "right"]):
        """Simulate a mousedown event on the targeted element.

        Arguments:
            selector: A CSS3 selector to targeted element
            btn: Mouse button
        """
        btn_id = dict(left=0, middle=1, right=2)[btn]
        return self.runJavaScript(f"""
            (function () {{
                var element = document.querySelector({selector!r});
                var evt = document.createEvent("MouseEvents");
                evt.initMouseEvent("mousedown", true, true, window,
                                   1, 1, 1, 1, 1, false, false, false, false,
                                   {btn_id!r}, element);
                return element.dispatchEvent(evt);
            }})();
        """)

    def set_input_value(self, selector: str, value):
        """Set the value of the input matched by given selector."""
        script = f'document.querySelector({selector!r}).setAttribute("value", "{value}")'
        self.runJavaScript(script)

find_text(string: str, backward: bool = False, case_sensitive: bool = False, callback: Callable[[bool], None] | None = None)

Find text in the current page.

Finds the specified string, subString, in the page, using the given options. The findTextFinished() signal is emitted when a string search is completed.

To clear the search highlight, just pass an empty string.

The resultCallback must take a boolean parameter. It will be called with a value of true if the subString was found; otherwise the callback value will be false.

Warning: It is guaranteed that the callback is always called, but it might be done during page destruction. When WebEnginePage is deleted, the callback is triggered with an invalid value and it is not safe to use the corresponding QWebEnginePage or QWebEnginePage instance inside it.

Parameters:

Name Type Description Default
string str

string to search for

required
backward bool

search backwards

False
case_sensitive bool

case-sensitive search

False
callback Callable[[bool], None] | None

result callback

None
Source code in prettyqt\webenginecore\webenginepage.py
def find_text(
    self,
    string: str,
    backward: bool = False,
    case_sensitive: bool = False,
    callback: Callable[[bool], None] | None = None,
):
    """Find text in the current page.

    Finds the specified string, subString, in the page, using the given options.
    The findTextFinished() signal is emitted when a string search is completed.

    To clear the search highlight, just pass an empty string.

    The resultCallback must take a boolean parameter.
    It will be called with a value of true if the subString was found;
    otherwise the callback value will be false.

    Warning: It is guaranteed that the callback is always called,
    but it might be done during page destruction. When WebEnginePage is deleted,
    the callback is triggered with an invalid value and it is not safe to use
    the corresponding QWebEnginePage or QWebEnginePage instance inside it.

    Args:
        string: string to search for
        backward: search backwards
        case_sensitive: case-sensitive search
        callback: result callback
    """
    if callback is None:

        def do_nothing(x):
            pass

        callback = do_nothing
    flag = webenginecore.QWebEnginePage.FindFlag(0)
    if case_sensitive:
        flag |= self.FindFlag.FindCaseSensitively
    if backward:
        flag |= self.FindFlag.FindBackward
    self.findText(string, flag, callback)

get_icon() -> gui.Icon | None

Return icon. If icon is Null, return None.

Source code in prettyqt\webenginecore\webenginepage.py
def get_icon(self) -> gui.Icon | None:
    """Return icon. If icon is Null, return None."""
    icon = self.icon()
    return None if icon.isNull() else gui.Icon(icon)

get_lifecycle_state() -> LifecycleStateStr

Get the current lifecycle state.

Source code in prettyqt\webenginecore\webenginepage.py
def get_lifecycle_state(self) -> LifecycleStateStr:
    """Get the current lifecycle state.

    Returns:
        lifecycle state
    """
    return LIFECYCLE_STATE.inverse[self.lifecycleState()]

get_scripts() -> webenginecore.WebEngineScriptCollection

Get script collection.

Source code in prettyqt\webenginecore\webenginepage.py
def get_scripts(self) -> webenginecore.WebEngineScriptCollection:
    """Get script collection."""
    return webenginecore.WebEngineScriptCollection(self.scripts())

get_setting(setting_name: webenginecore.webenginesettings.WebAttributeStr) -> bool

Return value of given WebEngine setting.

Source code in prettyqt\webenginecore\webenginepage.py
def get_setting(
    self,
    setting_name: webenginecore.webenginesettings.WebAttributeStr,
) -> bool:
    """Return value of given WebEngine setting."""
    return self.get_settings()[setting_name]

get_settings() -> webenginecore.WebEngineSettings

Get WebEngineSettings (a MutableMapping).

Source code in prettyqt\webenginecore\webenginepage.py
def get_settings(self) -> webenginecore.WebEngineSettings:
    """Get WebEngineSettings (a MutableMapping)."""
    settings = self.settings()
    return webenginecore.WebEngineSettings(settings)

insert_stylesheet(name: str, css: str | os.PathLike, immediately: bool = True)

Load css using JavaScript.

Parameters:

Name Type Description Default
name str

CSS id

required
css str | PathLike

CSS stylesheet, either a string or a PathLike object.

required
immediately bool

whther to run javascript immediately

True
Source code in prettyqt\webenginecore\webenginepage.py
def insert_stylesheet(
    self, name: str, css: str | os.PathLike, immediately: bool = True
):
    """Load css using JavaScript.

    Arguments:
        name: CSS id
        css: CSS stylesheet, either a string or a PathLike object.
        immediately: whther to run javascript immediately
    """
    if isinstance(css, os.PathLike):
        path = core.File(os.fspath(css))
        if not path.open(
            core.File.OpenModeFlag.ReadOnly | core.File.OpenModeFlag.Text
        ):
            return
        css = path.readAll().data().decode("utf-8")
    script = webenginecore.WebEngineScript()
    s = """
    (function() {
    css = document.createElement('style');
    css.type = 'text/css';
    css.id = "%s";
    document.head.appendChild(css);
    css.innerText = `%s`;
    })()
    """
    s = s % (name, css)
    script = webenginecore.WebEngineScript()
    if immediately:
        self.runJavaScript(s, script.ScriptWorldId.ApplicationWorld)
    script.setName(name)
    script.setSourceCode(s)
    script.setInjectionPoint(script.InjectionPoint.DocumentReady)
    script.setRunsOnSubFrames(True)
    script.setWorldId(script.ScriptWorldId.ApplicationWorld)
    self.scripts().insert(script)

load_url(url: datatypes.UrlType | datatypes.PathType)

Load the URL.

Loads the specified url and displays it.

Note: The Page remains the same until enough data has arrived to display the new URL.

Parameters:

Name Type Description Default
url UrlType | PathType

URL to load

required
Source code in prettyqt\webenginecore\webenginepage.py
def load_url(self, url: datatypes.UrlType | datatypes.PathType):
    """Load the URL.

    Loads the specified url and displays it.

    Note: The Page remains the same until enough data has arrived
    to display the new URL.

    Args:
        url: URL to load
    """
    self.load(datatypes.to_url(url))

mousedown(selector: str, btn: Literal['left', 'middle', 'right'])

Simulate a mousedown event on the targeted element.

Parameters:

Name Type Description Default
selector str

A CSS3 selector to targeted element

required
btn Literal['left', 'middle', 'right']

Mouse button

required
Source code in prettyqt\webenginecore\webenginepage.py
def mousedown(self, selector: str, btn: Literal["left", "middle", "right"]):
    """Simulate a mousedown event on the targeted element.

    Arguments:
        selector: A CSS3 selector to targeted element
        btn: Mouse button
    """
    btn_id = dict(left=0, middle=1, right=2)[btn]
    return self.runJavaScript(f"""
        (function () {{
            var element = document.querySelector({selector!r});
            var evt = document.createEvent("MouseEvents");
            evt.initMouseEvent("mousedown", true, true, window,
                               1, 1, 1, 1, 1, false, false, false, false,
                               {btn_id!r}, element);
            return element.dispatchEvent(evt);
        }})();
    """)

open_in_browser()

Open page URL in default system browser.

Source code in prettyqt\webenginecore\webenginepage.py
def open_in_browser(self):
    """Open page URL in default system browser."""
    try:
        webbrowser.open(self.getUrl().toString())
    except ValueError as e:
        logger.exception(e)

set_feature_permission(url: datatypes.UrlType, feature: FeatureStr | mod.Feature, policy: PermissionPolicyStr | mod.PermissionPolicy)

Set permission of feature for given URL.

Source code in prettyqt\webenginecore\webenginepage.py
def set_feature_permission(
    self,
    url: datatypes.UrlType,
    feature: FeatureStr | mod.Feature,
    policy: PermissionPolicyStr | mod.PermissionPolicy,
):
    """Set permission of feature for given URL."""
    url = core.Url(url)
    self.setFeaturePermission(
        url, FEATURE.get_enum_value(feature), PERMISSION_POLICY.get_enum_value(policy)
    )

set_input_value(selector: str, value: str)

Set the value of the input matched by given selector.

Source code in prettyqt\webenginecore\webenginepage.py
def set_input_value(self, selector: str, value):
    """Set the value of the input matched by given selector."""
    script = f'document.querySelector({selector!r}).setAttribute("value", "{value}")'
    self.runJavaScript(script)

set_lifecycle_state(state: LifecycleStateStr | mod.LifecycleState)

Set lifecycle state.

Parameters:

Name Type Description Default
state LifecycleStateStr | LifecycleState

lifecycle state

required
Source code in prettyqt\webenginecore\webenginepage.py
def set_lifecycle_state(self, state: LifecycleStateStr | mod.LifecycleState):
    """Set lifecycle state.

    Args:
        state: lifecycle state
    """
    self.setLifecycleState(LIFECYCLE_STATE.get_enum_value(state))

set_setting(setting_name: webenginecore.webenginesettings.WebAttributeStr, value: bool)

Set WebEngine setting to value.

Source code in prettyqt\webenginecore\webenginepage.py
def set_setting(
    self,
    setting_name: webenginecore.webenginesettings.WebAttributeStr,
    value: bool,
):
    """Set WebEngine setting to value."""
    self.get_settings()[setting_name] = value

set_url(url: datatypes.PathType | datatypes.UrlType)

Set the url of the WebEnginePage.

Clears the Page and loads the URL.

Parameters:

Name Type Description Default
url PathType | UrlType

URL to set

required
Source code in prettyqt\webenginecore\webenginepage.py
def set_url(self, url: datatypes.PathType | datatypes.UrlType):
    """Set the url of the WebEnginePage.

    Clears the Page and loads the URL.

    Args:
        url: URL to set
    """
    self.setUrl(datatypes.to_url(url))

set_zoom(zoom: float)

Set the zoom factor for the Page.

Valid values are within the range from 0.25 to 5.0. The default factor is 1.0.

Parameters:

Name Type Description Default
zoom float

Zoom factor

required
Source code in prettyqt\webenginecore\webenginepage.py
def set_zoom(self, zoom: float):
    """Set the zoom factor for the Page.

    Valid values are within the range from 0.25 to 5.0. The default factor is 1.0.

    Args:
        zoom: Zoom factor
    """
    self.setZoomFactor(zoom)

trigger_action(action: WebActionStr | mod.WebAction, checked: bool = False)

Trigger action.

Source code in prettyqt\webenginecore\webenginepage.py
def trigger_action(self, action: WebActionStr | mod.WebAction, checked: bool = False):
    """Trigger action."""
    self.triggerAction(WEB_ACTION.get_enum_value(action), checked)

⌗ Property table

Qt Property Type Doc
objectName QString
selectedText QString
hasSelection bool
requestedUrl QUrl
zoomFactor double
title QString
url QUrl
iconUrl QUrl
icon QIcon
backgroundColor QColor
contentsSize QSizeF
scrollPosition QPointF
audioMuted bool
recentlyAudible bool
visible bool
lifecycleState QWebEnginePage::LifecycleState
recommendedState QWebEnginePage::LifecycleState
renderProcessPid qlonglong
loading bool