加載QSS(十)

前言

在Qt中經常需要使用樣式,爲了降低耦合性(與邏輯代碼分離),我們通常會定義一個QSS文件,然後編寫各種控件(QLabel,QLIneEdit,QPushButton等)的樣式,最後使用QApplication或QMainWindow來加載樣式,這樣就可以讓整個應用程序共享一種樣式了

1 編寫QSS

首先新建一個擴展名爲.qss的文件,如style.qss,然後將其加入資源文件(.qrc)中,在style.qss文件中編寫樣式代碼,例如

QMainWindow{
        border-image:url(./images/screen1.jpg);

}

QToolTip{
        border: 1px solid rgb(45, 45, 45);
        background: white;
        color: red;
}

2 加載QSS

爲了方便以後使用,可以編寫一個公共類COmmomHelper,其核心代碼如下

class CommonHelper:
    def __init__(self):
        pass

    @staticmethod
    def readQss(style):
        with open(style, 'r') as f:
            return f.read()

然後在主函數進行加載,其核心代碼如下

app = QApplication(sys.argv)
    win = MainWindow()

    styleFile = './style.qss'
    qssStyle = CommonHelper.readQss(styleFile)
    win.setStyleSheet(qssStyle)

    win.show()
    sys.exit(app.exec_())

在換樣式時,不需要全局修改,只需要CommomHelper.readQSS()讀取不同的QSS文件即可

3 完整代碼如下

注意第一步的qss文件的建立,下面會用到


import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QVBoxLayout, QPushButton


class CommonHelper:
    def __init__(self):
        pass

    @staticmethod
    def readQss(style):
        with open(style, 'r') as f:
            return f.read()

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.resize(477, 258)
        self.setWindowTitle("加載QSS文件")
        btn1 = QPushButton(self)
        btn1.setText('添加')
        btn1.setToolTip('測試提示')
        vbox = QVBoxLayout()
        vbox.addWidget(btn1)

        self.setLayout(vbox)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()

    styleFile = './style.qss'
    qssStyle = CommonHelper.readQss(styleFile)
    win.setStyleSheet(qssStyle)

    win.show()
    sys.exit(app.exec_())

沒有加載樣式時,主窗口時這樣事的
這裏寫圖片描述
加載樣式後,主窗口是這樣事的
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章