Когда разрабатываете свой GUI с помощью PyQt для какого-либо софта бывает необходимо позаимствовать цвета из текущего стиля интерфейса. Например, чтобы правильно раскрасить свои виджеты, подогнав их по цвету. Ведь бывает, что ваш GUI используется в разных софтах. Причём некоторые со светлой темой а другие с тёмной.
По умолчанию стили наследуются, но если вы задаёте какую-либо раскраску для части виджета через свой styleSheet, то требуется ссылаться на цвета текущего стиля.
Как это сделать? Как получить нужный цвет из палитры имеющегося стиля? Это достаточно просто, нужно использовать класс QPalette и его роли.
Например, мне нужно достать цвет текста из одного виджета и применить его в другом как цвет фона (не важно зачем именно так, просто захотелось😊).
Получаем палитру виджета и сразу достаём нужный цвет, указав его роль.
from PySide2.QtGui import QPalette
color = main_window.palette().color(QPalette.Text)
теперь можем использовать этот цвет в стилях
my_widget.setStyleSheet(f'background-color: {color.name()};')
Готово, мы динамически переопределили дефолтный стиль используя текущий стиль окна!
На самом деле есть запись покороче, в одну строку и без лишних переменных. Не очень-то по правилам CSS, но Qt это понимает.
my_widget.setStyleSheet('background-color: palette(Text);')
Этот способ не подходит если вам нужно как-то модифицировать цвет перед применением в своих стилях. В этом случае потребуется первый способ.
Зато он прекрасно сработает в файле .qss, то есть не придётся в коде прописывать раскраску отдельных элементов через ссылки на палитру, всё красиво сохранится в отдельном файле .qss!
QListView#my_widget::item:selected {
background: palette(Midlight);
}
Про имеющиеся роли можно почитать здесь🌍
#qt#tricks
🇺🇿Biznes va tadbirkorlik oliy maktabi 9-may – Xotira va qadrlash kuni bilan barchangizni chin dildan qutlaydi!
🗓 9-may – Xotira va qadrlash kuni munosabati bilan Vatanimiz tinchligi va farovonligi uchun jang maydonlarida buyuk qahramonlik ko‘rsatib, halok bo‘lgan mo‘tabar ota-bobolarimizni xotirasi barhayot bo‘lsin, front ortida fidokorona mehnat qilgan faxriylarimizni hamda butun xalqimizni samimiy muborakbod etamiz!
⏩ O‘z navbatida, urushdan keyin mamlakatni tiklash, jonajon O‘zbekistonimizni rivojlantirishga munosib hissa qo‘shib kelayotgan, tabarruk yoshga yetib, duogo‘yimiz bo‘lib yurgan nuroniy otaxonu onaxonlarimizga cheksiz minnatdorligimizni bildiramiz.
🟥 Vatanimiz tinch, osmonimiz musaffo, mustaqilligimiz abadiy bo‘lsin aziz Yurtdoshlar!
#GraduateSchool#Remembrance#Appreciation
🌐Web-site |
✅ Telegram |
✅Facebook |
🌐Instagram
Standing in remembrance of those who gave their lives for freedom.
To remember is to refuse indifference, and to defend the dignity and freedoms they died for.
面對今日仇恨與極右思潮再次抬頭,自問若為自由犧牲的靈魂泉下有知,會如何期望我們守護得來不易的價值?
#Remembrance#LestWeForget#永誌不忘
US Condemns Crocus City Hall Terror Attack on Anniversary
The US Embassy in Russia marked the second anniversary of the Crocus City Hall tragedy, expressing solidarity with victims’ families. The March 22, 2024 terror attack claimed 151 lives, including children, profoundly affecting many. The US emphasized that the memory of those lost remains strong over time.
#terrorattack#Crocus#USA#Russia#remembrance
The main news of Russia and the world ishere.
前往 #和平紀念日 典禮的乘客
可取道 #中環 站 出口 J3 - 香港會所大廈
#中環 站出口位置 👉metroride.hk/3F89wcu
該站 出口 J1 - 終審法院 將於 11 月 10 日(星期日) 10:00 關閉至 12:00 為止,使進出街道的人流更為暢順 🌺
#LestWeForget
#英魂不朽#永誌不忘
Use Exit J3 - The Hong Kong Club Building for #Remembrance Day Ceremony
Exit locations of Central 👉metroride.hk/3F89wcu
While Exit J1 - The Court of Final Appeal will be closed from 10:00 - 12:00, 10/Nov (Sun) for a smoother passenger flow to and from street level 🌺
Musical and Poetic Performance “The Spring is Coming Again to the World…”
On the eve of Victory Day, the Russian House in Brussels invites you to a special evening of music and poetry.
People’s Artist of Russia Oleg Pogudin and his Romance Theatre will present a programme dedicated to the memory of a generation whose youth fell upon the years of the Great Patriotic War.
The evening will feature poems and songs born in the harsh years of war — sincere, courageous, and filled with both the pain of loss and a bright hope.
🎹 Piano part: Oleg Weinstein, Honored Artist of the Russian Federation
📅 April 28
🕖 19:00–21:00
📍 Russian House in Brussels
🎟 Free admission upon registration
https://rushouse.be/event/musical-performance-the-spring-is-coming-again-to-the-world/
We warmly invite you to join this evening of remembrance, music, and poetry.
#RussianHouseBrussels#BrusselsEvents#Culture#Music#Poetry#OlegPogudin#Concert#CulturalDiplomacy#VictoryDay#Remembrance#RussianCulture#ArtAndCulture