Skip to content

Instantly share code, notes, and snippets.

@StephenNneji
Last active August 23, 2023 14:34
Show Gist options
  • Save StephenNneji/3390e012eb7d73a8b381a9c94302217c to your computer and use it in GitHub Desktop.
Save StephenNneji/3390e012eb7d73a8b381a9c94302217c to your computer and use it in GitHub Desktop.
Simple theme icon switching using the QIconEgine
"Based on https://stackoverflow.com/a/76096769"
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QToolButton, QComboBox, QVBoxLayout, QHBoxLayout
from PyQt6.QtGui import QIcon, QIconEngine, QPainter
from PyQt6.QtCore import QSize, QRect
themes = ['light', 'dark']
active_theme = themes[0]
light = '''
* {
font-family:"Helvetica Neue", Helvetica, Arial;
font-size: 12px;
color: #333;
background-color: rgb(240, 240, 240);
}
'''
dark = '''
* {
font-family:"Helvetica Neue", Helvetica, Arial;
font-size: 12px;
color: rgb(255, 255, 255);
background-color: rgb(52, 49, 49);
}
'''
def get_theme_path():
# modify this to have the light and dark folder
if active_theme == themes[1]:
return 'dark/'
return ''
class IconEngine(QIconEngine):
def __init__(self, file_name):
super().__init__()
self.theme = active_theme
self.icon = QIcon(file_name)
self.file_name = file_name
def updateIcon(self):
if self.theme != active_theme:
# path should be created with pathlib but this is quick
path = f'{get_theme_path()}{self.file_name}'
self.icon = QIcon(path)
self.theme = active_theme
def pixmap(self, size, mode, state):
self.updateIcon()
return self.icon.pixmap(size, mode, state)
def paint(self, painter, rect, mode, state):
self.updateIcon()
return self.icon.pixmap.paint(painter, rect, mode, state)
def changeStyle(name):
global active_theme
if name == themes[0]:
QApplication.instance().setStyleSheet(light)
else:
QApplication.instance().setStyleSheet(dark)
active_theme = name
class Window(QWidget):
def __init__(self):
super().__init__()
but1 = QToolButton()
but2 = QToolButton()
icon1 = QIcon(IconEngine('unchecked.png'))
icon2 = QIcon(IconEngine('checked.png'))
but1.setIcon(icon1)
but2.setIcon(icon2)
cmb = QComboBox()
cmb.addItems(themes)
cmb.currentTextChanged.connect(changeStyle)
changeStyle(themes[0])
tbs = QHBoxLayout()
tbs.addWidget(but1)
tbs.addWidget(but2)
lay = QVBoxLayout(self)
lay.addWidget(cmb)
lay.addLayout(tbs)
app = QApplication([])
window = Window()
window.show()
sys.exit(app.exec())
@StephenNneji
Copy link
Author

Screenshot 2023-08-18 094204
Screenshot 2023-08-18 094317

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment