c++qtqwebviewqwebkit

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?


Solution

  • 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:

    Put this in your "main.cpp":

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