WebEngine StyleSheet 瀏覽器範例

演示如何以用戶腳本把 CSS 注入網頁。

StyleSheet Browser 演示如何使用 Qt WebEngine C++ 類 去把用戶樣式錶注入網頁。

運行範例

要運行範例從 Qt Creator ,打開 歡迎 模式,然後選擇範例從 範例 。更多信息,拜訪 構建和運行範例 .

操控樣式錶

We use JavaScript to create and append CSS elements to the documents. After declaring the script source, QWebEnginePage::runJavaScript () can run it immediately and apply newly created styles on the current content of the web view. Encapsulating the script into a QWebEngineScript and adding it to the script collection of QWebEnginePage makes its effect permanent.

void MainWindow::insertStyleSheet(const QString &name, const QString &source, bool immediately)
{
    QWebEngineScript script;
    QString s = QString::fromLatin1("(function() {"\
                                    "    css = document.createElement('style');"\
                                    "    css.type = 'text/css';"\
                                    "    css.id = '%1';"\
                                    "    document.head.appendChild(css);"\
                                    "    css.innerText = '%2';"\
                                    "})()").arg(name).arg(source.simplified());
    if (immediately)
        ui->webEngineView->page()->runJavaScript(s, QWebEngineScript::ApplicationWorld);
    script.setName(name);
    script.setSourceCode(s);
    script.setInjectionPoint(QWebEngineScript::DocumentReady);
    script.setRunsOnSubFrames(true);
    script.setWorldId(QWebEngineScript::ApplicationWorld);
    ui->webEngineView->page()->scripts().insert(script);
}
					

Removing stylesheets can be done similarly:

void MainWindow::removeStyleSheet(const QString &name, bool immediately)
{
    QString s = QString::fromLatin1("(function() {"\
                                    "    var element = document.getElementById('%1');"\
                                    "    element.outerHTML = '';"\
                                    "    delete element;"\
                                    "})()").arg(name);
    if (immediately)
        ui->webEngineView->page()->runJavaScript(s, QWebEngineScript::ApplicationWorld);
    QWebEngineScript script = ui->webEngineView->page()->scripts().findScript(name);
    ui->webEngineView->page()->scripts().remove(script);
}
					
					

文件和歸屬

範例使用的圖標來自 Tango 圖標庫:

Tango 圖標庫 公共領域

範例工程 @ code.qt.io