Username Obfuscation
Username Obfuscation

Reputation: 776

How to modify the -webkit-scrollbar styles in a QWebView

Webkit provides special css properties for styling scrollbars, for example:

::-webkit-scrollbar-track {
    background-color:white;
}

Normally I'd put these inside a <style> tag inside <head>, but unfortunately QWebElement doesn't seem to be able to modify anything inside <head>. I can use the setHtml() function to specify initial styling, but not modify it later. Is there an alternative way to apply CSS styles to the scrollbars in a QWebFrame?

Upvotes: 1

Views: 1885

Answers (1)

Korvo
Korvo

Reputation: 9754

Is possible using QWebSettings::setUserStyleSheetUrl, see example:

const QString path = PATH_OF_CSS_FILE;
QWebSettings *settings = QWebSettings::globalSettings();
settings->setUserStyleSheetUrl(QUrl(path));

Example

If dynamic CSS is a string, you can create a method and use QTemporaryFile, like this:

void MainWindow::setStyle(const QString data)
{
    QTemporaryFile file;
    if (file.open()) {
        const QString path = file.fileName();

        QWebSettings *settings = QWebSettings::globalSettings();
        settings->setUserStyleSheetUrl(QUrl(path));
    }
}

Usage:

setStyle("::-webkit-scrollbar-track { background-color:white;}")

If needs load dynamic file, you can create an alternative method like this:

void MainWindow::setStyle(const QUrl url)
{
    QWebSettings *settings = QWebSettings::globalSettings();
    settings->setUserStyleSheetUrl(url);
}

Using QRC

Is part of the answer is just a tip for other implementations;

You can use resources (QRC) in your project for put default stylesheet for all QWebViews, see example:

  • Click right button in your project > Add New ... > Qt > Qt Resource File > Put name "resources.qrc"

  • Click right button in "resources.qrc" > Open in Editor

  • Put a CSS file with name scrollbar.css (css file must be in the same folder as your project).

Put this in your "main.cpp":

#include <QWebSettings>
#include <QUrl>

...

const QString path = "qrc:/scrollbar.css";
QWebSettings *settings = QWebSettings::globalSettings();
settings->setUserStyleSheetUrl(QUrl(path));

Upvotes: 1

Related Questions