Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QWebView not loading external CSS

I am using a QWebView to display some content and I want to use custom CSS to spruce up the output. I found that I can use the QWebSettings.setUserStyleSheetUrl() method to load my own CSS into the view. The .css file is in the same directory as my main program.

self.webview = QWebView(MainWindow)
self.webview.settings().setUserStyleSheetUrl(QUrl.fromLocalFile("myCustom.css"))

However, the custom stylings don't load when I add the content to the page using setHtml(). I have tested that the CSS is properly applying to the HTML in a standard browser.

Any idea what I am doing wrong?

like image 650
swanson Avatar asked Sep 16 '25 03:09

swanson


2 Answers

In Qt, all paths to external files need to be ABSOLUTE paths, not relative ones.

To fix the problem, I add to make the following change:

path = os.getcwd()
self.webview.settings().setUserStyleSheetUrl(QUrl.fromLocalFile(path + "/myCustom.css"))

And everything worked correctly. Hopefully this will help someone in the future and save them a few hours debugging.

like image 188
swanson Avatar answered Sep 17 '25 15:09

swanson


In Qt, all paths to external files need to be ABSOLUTE paths, not relative ones.

That's not true. The code below works for me.

#include <QtCore>
#include <QtGui>
#include <QtWebKit>

int main(int argc, char ** argv)
{
    QApplication app(argc, argv);

    QMainWindow mainWindow;

    QWebView* webView = new QWebView(&mainWindow);
    webView->settings()->setUserStyleSheetUrl(QUrl::fromLocalFile("google.css"));

    QFile source("google.html");
    source.open(QIODevice::ReadOnly);
    webView->page()->mainFrame()->setHtml(QString::fromUtf8(source.readAll().constData()));

    mainWindow.setCentralWidget(webView);
    mainWindow.show();

    return app.exec();
}

The .css file is in the same directory as my main program.

Relative paths are interpreted relative to the current working directory which need not be the same as executable's directory.

like image 41
Piotr Dobrogost Avatar answered Sep 17 '25 16:09

Piotr Dobrogost