使用 python 格式化工具解析和修改 Qt 样式表可能很复杂,例如在您尝试格式化(0, 0, 0, 50%)
导致错误的情况下,因此我建议使用qstylizer
( python -m pip install qstylizer
),以便您可以轻松修改属性:
QTabBar::close-button {
padding: 0px;
margin: 0px;
border-radius: 2px;
border-color: rgba(0, 0, 0, 50%);
background-position: center center;
background-repeat: none;
}
import functools
from fbs_runtime.application_context.PyQt5 import ApplicationContext
import qstylizer.parser
customIcons = {
"QTabBar.closeButton.backgroundImage": f"url({app.get_resource('ui/close.png')})",
}
app = ApplicationContext()
with open(app.get_resource("app.qss"), "r") as stylesheet:
css = qstylizer.parser.parse(stylesheet.read())
for key, value in customIcons.items():
obj = functools.reduce(getattr, key.split("."), css)
obj.setValue(value)
app.app.setStyleSheet(css.toString())
更新:
分析源代码:
if key and key[0] not in ["Q", "#", "[", " "] and not key.istitle():
key = inflection.underscore(key)
似乎这些类是TitleCase所以一个可能的解决方案是将类的名称更改为Customtabbar
:
Customtabbar::close-button {
padding: 0px;
margin: 0px;
border-radius: 2px;
border-color: rgba(0, 0, 0, 50%);
background-position: center center;
background-repeat: none;
}
app = ApplicationContext()
customIcons = {
"Customtabbar::close-button": {
"background-image": f"url({app.get_resource('ui/close.png')})"
},
}
with open(app.get_resource("app.qss"), "r") as stylesheet:
css = qstylizer.parser.parse(stylesheet.read())
for qcls, value in customIcons.items():
for prop, v in value.items():
css[qcls][prop] = v
app.app.setStyleSheet(css.toString())
根据 PEP,类名必须是 CapWords,所以我通过更改创建了一个分支:
qstylizer/style.py
if key and key[0] not in ["Q", "#", "[", " "] and not key.istitle():
经过
if key and key[0] not in ["Q", "#", "[", " "] and key != inflection.camelize(key):
现在接受符合 PEP8 的类的名称。
CustomTabBar::close-button {
padding: 0px;
margin: 0px;
border-radius: 2px;
border-color: rgba(0, 0, 0, 50%);
background-position: center center;
background-repeat: none;
}
app = ApplicationContext()
customIcons = {
"CustomTabBar::close-button": {
"background-image": f"url({app.get_resource('ui/close.png')})"
},
}
with open(app.get_resource("app.qss"), "r") as stylesheet:
css = qstylizer.parser.parse(stylesheet.read())
for qcls, value in customIcons.items():
for prop, v in value.items():
css[qcls][prop] = v
app.app.setStyleSheet(css.toString())
更新2:
PR已被接受,因此只需要更新库:python -m pip install qstylizer --upgrade
.