Когда разрабатываете свой 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
🥇🏆 The Moment of Glory!
A proud scene from the podium at the Asian Cadet Fencing Championships – Kuala Lumpur 2025 🇲🇾⚔️
From Hong Kong to Kazakhstan and Uzbekistan, fencers shined with skill, passion, and true sportsmanship 💪
Congratulations to the Men’s Foil medalists on an outstanding performance and well-deserved victories! 👏
🥇 HO Shing Him Harris 🇭🇰
🥈 LAM Ho Long 🇭🇰
🥉 NURUMOV Galim 🇰🇿
🥉 MOLINA Ilyas 🇺🇿
#Fencing#AsianFencing#MensFoil#KualaLumpur#FencingAsia#Championships#FencingSpirit
Cadet Asian Cup 2025 — Tashkent, Uzbekistan 🇺🇿
✅ Day 1 Results — Cadet Women’s Sabre
1️⃣ RUZIEVA Salima 🇺🇿
2️⃣ KHUSANBOEVA Bibiaisha 🇺🇿
3️⃣ ISKHAKOVA Nailya 🇰🇿
3️⃣ MAUINBERGENOVA Perizat 🇺🇿
👏 Congratulations to the winners and all participants!
👉 Stay tuned and follow us for daily updates!
#CadetAsianCup#FencingAsia#FCA#FIE#Tashkent2025#Sabre#Fencing#AsiaFencing
Cadet Asian Cup 2025 — Tashkent, Uzbekistan 🇺🇿
✅ Day 1 Results — Cadet Men’s Foil
1️⃣ ALBUSAIDI Ali 🇴🇲
2️⃣ CHEONG Pak Kio 🇲🇴
3️⃣ YETSEU Mansur 🇰🇿
3️⃣ TOKANOV Yevgeniy 🇰🇿
👏 Congratulations to the winners and all participants!
👉 Stay tuned and follow us for daily updates!
#CadetAsianCup#FencingAsia#FCA#FIE#Tashkent2025#Foil#Fencing#AsiaFencing
⏳ Countdown is on!
Only 26 days left until one of Asia’s biggest fencing showdowns! 🌏🤺
📍 Bali – Indonesia
📆 June 17–23, 2025
🏆 Senior Asian Fencing Championship
Top athletes are getting ready for an electrifying competition!
Stay tuned for full access 📸 and live highlights from the heart of the action 🎥🔥
#Fencing⚔️#Bali2025#AsianChampionship
#FCA#FIE#SeniorAsianFencingChampionship2025
#Indonesia#FencingAsia#Countdown
🏆 Asian Senior Fencing Championship – Bali 2025 🗡️
This is where legends are forged ✨
Where pleasure 🎉, dignity 🛡️, and the spirit of competition 🔥 collide!
The thrill of victory 🥇, the clash of steel ⚔️, and the soul of competition 🏃♂️
All in one place — glory carved in blades, legends born in every touch ⚡
#Bali welcomes the elite 🤺
#AsianFencingChampionship 2025 🌏
#FCA#FencingAsia#Bali2025
#FencingPower#BladesOfGlory#Honor#AsianFencing
🌴 Bali – where stunning beaches and rich culture come together!
✨ Relax by the ocean, explore vibrant local life, and feel the magic of sacred temples.
🏝️ This June, experience the Asian Senior Fencing Championships 2025
⚔️ World-class fencing meets unforgettable views!
📅 June 17–23
📍 Bali, Indonesia
#AsianFencingChampionships
#FencingAsia
#Bali2025
#Indonesia
#FCA#FIE
#Fencing#SportsTravel
#NatureAndSport#EpicViews
🔟 Only 10 Days to Go!
The countdown has begun for Asia’s ultimate fencing spectacle ⚔️🌏
Get ready as the 2025 Asian Senior Fencing Championships land on the breathtaking island of Bali! 🌺🌴
📍 Bali, Indonesia 🇮🇩
📅 June 17–23, 2025
⏳ Seven days. One stage. Endless glory.
✨ Witness:
⚡ Elite fencers from across Asia battle for supremacy
🔥 Unforgettable showdowns & rivalries reborn
🥇 New legends rising — champions forged in every bout
🎯 Precision. Passion. Power. Every point is everything.
📡 Stay tuned for:
🔴 Live updates
🎞️ Daily highlights
🎥 Behind-the-scenes action
📸 Exclusive content you won’t want to miss!
🚀 The road to greatness starts now — and it leads through Bali.
Don’t just watch history… be part of it.
🔽 Follow us & gear up for the fight of the year!
#AsianFencing#Bali2025#UnleashTheBlade
#CountdownToGlory#FencingAsia#SeniorFencing
#ChampionsRise#BladesOfAsia#FIE#TopFencers
#Indonesia#FencingElite#RoadToVictory#AFC