PyQt5学习笔记9_使用setStyle和setStyleSheet进行换肤

通过QStyleFactory.keys()可获取用于setStyle的有效值,本例程中包含“Windows”,“WindowsXP”,“WindowsVista”,“Fusion”四种风格,此外,还使用了setStyleSheet对一款黑色主题“QDarkStyleSheet”进行加载,即可以在以上5种界面风格之间切换。
效果如下:
PyQt5学习笔记9_使用setStyle和setStyleSheet进行换肤_第1张图片
代码如下:

import sys
from os.path import join, dirname, abspath
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow, QStyleFactory
import qdarkstyle

_UI = join(dirname(abspath(__file__)), 'mainwindow.ui')


class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        uic.loadUi(_UI, self)


class Application(QApplication):
    def __init__(self, argv):
        QApplication.__init__(self, argv)

    def _slot_setStyle(self):
        app.setStyleSheet('')
        tmp = self.sender().objectName()[6:]
        if tmp in QStyleFactory.keys():
            app.setStyle(tmp)
        elif tmp == 'Qdarkstyle':
            app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())


if __name__ == '__main__':
    app = Application(sys.argv)
    w = MainWindow()
    w.actionWindows.triggered.connect(app._slot_setStyle)
    w.actionWindowsXP.triggered.connect(app._slot_setStyle)
    w.actionWindowsVista.triggered.connect(app._slot_setStyle)
    w.actionFusion.triggered.connect(app._slot_setStyle)
    w.actionQdarkstyle.triggered.connect(app._slot_setStyle)
    w.show()
    sys.exit(app.exec_())

相关链接:
PyQt5学习笔记7_QDarkStyleSheet

你可能感兴趣的:(Qt,Python)