Demonstrates how to inject CSS into web pages using user scripts.
StyleSheet Browser demonstrates how to use the Qt WebEngine C++ classes to inject user stylesheets into web pages.
To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example.
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); const QList<QWebEngineScript> scripts = ui->webEngineView->page()->scripts().find(name); if (!scripts.isEmpty()) ui->webEngineView->page()->scripts().remove(scripts.first()); }
The example uses icons from the Tango Icon Library:
Tango Icon Library | Public Domain |
As part of the free Business evaluation, we offer a free welcome call for companies, to talk about your requirements, and how the Felgo SDK & Services can help you. Just sign up and schedule your call.
Sign up now to start your free Business evaluation: