QWebEngineView本身没有提供设置滚动条样式的接口,可以通过注入js代码来实现自定义滚动条的样式。
准备好一个qss文件scrollbarstyle.css放置到资源目录
::-webkit-scrollbar-thumb {
border: 2px solid transparent;
background-clip: padding-box;
background-color: rgba(31,35,41,.3);
border-radius: 9999px;
-webkit-transition: background .2s cubic-bezier(.34,.69,.1,1);
transition: background .2s cubic-bezier(.34,.69,.1,1)
}
::-webkit-scrollbar {
width: 12px;
height: 12px;
background-color: transparent
}
::-webkit-scrollbar-button {
display: none
}
::-webkit-scrollbar-corner,::-webkit-scrollbar-track {
background-color: transparent
}
::-webkit-scrollbar-thumb:hover {
background-color: rgba(31,35,41,.6)!important
}
::-webkit-scrollbar:hover {
width: 12px;
height: 12px
}
窗口QWebEengineView后调用一下代码端实现js代码注入:
QWebEngineView *pWebView = new QWebEngineView();
//自定义浏览器滚动条样式
QFile cssfile(":/scrollbarstyle.css");
if (cssfile.open(QFile::ReadOnly)) {
QTextStream stream(&cssfile);
const QString styleJS = QString::fromLatin1("(function() {"\
" css = document.createElement('style');"\
" css.type = 'text/css';"\
" css.id = '%1';"\
" document.head.appendChild(css);"\
" css.innerText = '%2';"\
"})()\n").arg("scrollbarStyle").arg(stream.readAll().simplified());
cssfile.close();
QWebEngineScript script;
script.setWorldId(QWebEngineScript::MainWorld);
script.setSourceCode(styleJS);
pWebView->page()->scripts().insert(script);
pWebView->page()->runJavaScript(styleJS, QWebEngineScript::ApplicationWorld);
}
这样加载网页就能把默认样式改成自定义样式了。