写一个类定义两个静态方法加载qss,第一种通过文件相对路径加载, 第二种通过资源文件路径加载
from PyQt5.QtCore import QFile, QIODevice, QTextStream
class CommonHelper:
def __init__(self):
pass
#根据文件路径读取qss
@staticmethod
def readQssFile(file_path):
with open(file_path, 'r') as f:
return f.read()
#从资源文件读取qss
@staticmethod
def readQssResource(resource_path):
stream = QFile(resource_path)
stream.open(QIODevice.ReadOnly)
return QTextStream(stream).readAll()
然后调用
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QApplication
from cmain import *
from common_utils import CommonHelper
if __name__ == "__main__":
app = QApplication(sys.argv)
mainwidget = CWidgetMain(None)
styleFile = ":/qss/monitor.qss" #根据资源文件路径加载
#styleFile = "./qss/monitor.qss" #根据文件路径加载
qssStyle = CommonHelper.readQssResource(styleFile)
mainwidget.setStyleSheet(qssStyle)
mainwidget.show()
sys.exit(app.exec_())