1. 程式人生 > 程式設計 >python GUI庫圖形介面開發之PyQt5動態載入QSS樣式檔案

python GUI庫圖形介面開發之PyQt5動態載入QSS樣式檔案

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

編寫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;
}

載入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檔案即可

完整程式碼如下

注意第一步的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_())

沒有載入樣式時,視窗樣式

python GUI庫圖形介面開發之PyQt5動態載入QSS樣式檔案

載入樣式後,視窗樣式

python GUI庫圖形介面開發之PyQt5動態載入QSS樣式檔案

本文介紹瞭如何在視窗執行狀態下動態載入QSS樣式檔案改變視窗樣式,更多關於QSS樣式的文章請檢視下面的相關連結