PySide2应用中使用CSS自定义属性(变量)时样式解析失败
问题原因及解决方案
核心错误点
- Qt样式表(QSS)不支持CSS变量和
:root选择器:你用的--dark这类自定义属性和:root是标准CSS特性,但QSS并不兼容,这是样式表解析失败的主要原因。 border-radius语法错误:QSS中多个圆角值需要用空格分隔,而非逗号。- 占位符选择器不兼容:标准CSS的
::placeholder在QSS中无效,需改用QLineEdit::placeholder-text。 - QMainWindow布局问题:QMainWindow默认没有顶层布局,直接调用
self.layout()会返回None,无法添加部件。 - 样式未刷新:设置部件的自定义property后,需要手动触发样式刷新才能生效。
修正后的代码
import sys, re from module.widgets import RuWidgets from module.functions import * from module.statics import * from PySide2.QtGui import QFont, QFontDatabase, QIcon, QCursor from PySide2.QtCore import Qt, Signal, QThread, QPoint, QSettings from PySide2.QtWidgets import QApplication, QMainWindow, QFrame, QMenu, QLineEdit, QWidget, QVBoxLayout class Patrick(QMainWindow): custom_colors = None def __init__(self): super().__init__() data = readJSON(CONFIGURATION, 'data') self.setWindowFlag(Qt.FramelessWindowHint) self.setAttribute(Qt.WA_TranslucentBackground) self.setWindowTitle(NAME) self.setFixedSize(WIDTH, HEIGHT) # 替换CSS变量为直接写值,修正QSS语法 self.setStyleSheet( """ #normal { background-color: #483939; color: #D9D9D9; } #inverted { background-color: #D9D9D9; color: #483939; } .full_rounded { border-radius: 8px 8px 8px 8px; } .top_rounded { border-radius: 0px 0px 8px 8px; } QLineEdit::placeholder-text { color: #9C8181; } """ ) # 给QMainWindow设置中心部件和布局 central_widget = QWidget() self.setCentralWidget(central_widget) layout = QVBoxLayout(central_widget) layout.setContentsMargins(0, 0, 0, 0) # 去掉默认边距 background = QFrame() background.setFixedSize(WIDTH, HEIGHT) bar = QFrame() bar.setFixedSize(WIDTH, WIDGET_HEIGHT) for widget, object_name, object_class in [ (background, 'normal', 'full_rounded'), (bar, 'inverted', 'top_rounded') ]: widget.setObjectName(object_name) widget.setProperty(object_class, True) # 设置property后刷新样式 widget.style().unpolish(widget) widget.style().polish(widget) for widget in [ background, bar ]: layout.addWidget(widget) self.show() if __name__ == '__main__': application = QApplication(sys.argv) window = Patrick() #font = QFont( # QFontDatabase.applicationFontFamilies( # QFontDatabase.addApplicationFont( # FONT.format('Inter-Regular') # ) # )[0] #) #font.setPointSize(FONT_SIZE) # 修正:pointSize()是获取值,设置用setPointSize() #application.setFont(font) application.exec_()
额外说明
如果想实现类似CSS变量的复用效果,可以用Python变量拼接样式表,避免重复写颜色值:
dark_color = "#483939" middle_color = "#9C8181" light_color = "#D9D9D9" style_sheet = f""" #normal {{ background-color: {dark_color}; color: {light_color}; }} #inverted {{ background-color: {light_color}; color: {dark_color}; }} QLineEdit::placeholder-text {{ color: {middle_color}; }} """ self.setStyleSheet(style_sheet)
内容的提问来源于stack exchange,提问作者Berdy Alexei Cadaeib Fecei
相关产品推荐
相关产品推荐

