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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With