Когда разрабатываете свой 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
🌟Thinking of applying for the IRAS scholarship?
Get insider tips from our current scholars to help with your application. ✍️ Don’t miss this opportunity to contribute meaningfully to Singapore’s economic and social growth. Apply to be an IRAS scholar at go.gov.sg/scholarapply by 31 March 2026.
#IRASscholarships#scholarships
Where tax builds tomorrow. 🇸🇬
Our scholars Nathaniel, Jing Rong, and Yern-Wei share about their journey in IRAS and how their work drives Singapore’s economic growth and inclusive society. Join us and discover diverse, purpose-driven careers that foster dynamic learning and collaborative innovation!
Watch the full video here: https://youtu.be/sHnS6XFP-HA?si=m-uuab47jrjnr47H
✍️ Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#IRASscholarships#scholarships
Where every expertise matters. 💼
At IRAS, we bring together different disciplines and unique specialists to work on projects that drives Singapore’s economic growth. IRAS scholarships are open to students from diverse areas of study.
Watch the full video here: https://youtu.be/sHnS6XFP-HA?si=m-uuab47jrjnr47H
Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#IRASscholarships#scholarships
Where tax builds tomorrow.💡
With pre-filled forms containing income details and tax reliefs, filing taxes is done in a matter of minutes. But what goes on behind-the-scenes to create this smooth taxpaying experience? Meet IRAS Director Leong Shi Wei, who leads multidisciplinary teams that oversee data policy, governance, and digital partnerships - making paying taxes a seamless and automated experience. Learn more about his work at IRAS here: https://go.gov.sg/iras-designing-the-tax-experience
Ready to collaborate with diverse teams on projects of national importance? 🇸🇬Apply to be an IRAS scholar today at go.gov.sg/scholarapply. Applications close on 31 Mar 2026.
#IRASscholarships#scholarships
Where every expertise matters.🧪
At IRAS, we bring together diverse and unique disciplines and specialists to drive projects that shape Singapore’s future. Meet Charmaine Tan, an IRAS scholar pursuing her Bachelor of Science in Life Sciences and Minor in Forensic Science, as she shares how her academic passion translates into meaningful impact.
Ready to put your expertise towards nation-building? 🌟 Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#IRASscholarships#scholarships
Where growth knows no limits. 🌱
What does it mean to be an IRAS scholar? Meet Shaine Goh (Software Engineer, Infocomm Division) whose journey with the IRAS Merit Undergraduate Scholarship turned her potential into real-world impact. 💼 From computing skills to transforming tax services, Shaine shows how innovation can reshape the taxpayer experience. Read her story: go.gov.sg/iras-shaine-goh
At IRAS, we invest in your personal growth so you can maximise your full potential. Ready to grow without limits? ✨ Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#scholarships#IRASscholarships
Where tax builds tomorrow.
IRAS scholarships are your gateway to a meaningful career that propels Singapore’s economic growth forward. Take your first step with us and unlock endless possibilities.
Ready to shape tomorrow? Learn more about life at IRAS at go.gov.sg/lifeatiras and visit go.gov.sg/scholarapply to apply to be an IRAS scholar via BrightSparks today.
#scholarships#IRASscholarships
🌐 As a Tax Director in IRAS’ Corporate Tax Division, IRAS scholar Joanne Tan refines tax laws and shapes policies that strengthen Singapore’s economic future, while leading a team of officers to discover the dynamic side of tax work. Learn more about her journey at IRAS here.
Apply for IRAS scholarships today at go.gov.sg/scholarapply
#lifeatIRAS#IRASscholarships#scholarships
Have questions about IRAS Scholarships? We’re here to answer them. 💬
Our scholarship application is now open, so don’t miss out! Apply today at go.gov.sg/scholarapply.
For more details, feel free to reach out to us at [email protected].
#IRASscholarships#scholarship#lifeatiras
📢 Calling all A-level/IB graduates and university students from all disciplines!
Catch a glimpse of life as an IRAS intern – follow our scholar Gerald Wong through his #dayinthelife.
Ready to make a difference? Join our future-ready #IRASFam and do work that matters in a collaborative, empowering environment. 🚀 Apply for IRAS scholarships at go.gov.sg/scholarapply or internships at www.careers.gov.sg today.
#lifeatIRAS#IRASscholarships