Last active
August 23, 2023 14:34
-
-
Save StephenNneji/3390e012eb7d73a8b381a9c94302217c to your computer and use it in GitHub Desktop.
Simple theme icon switching using the QIconEgine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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()) |
Author
StephenNneji
commented
Aug 18, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment