Когда разрабатываете свой 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
🎓✨ CONGRATULATIONS! ✨🎓
To all Jimma University students who passed the exit exam and will graduate this Saturday! 🌟
Your hard work and determination have led to this proud moment. Wishing you a future full of success, peace, and new beginnings! 🌍🎉
#JIFAR CAREER
Eid Mubarak! ✨ May this special day bring you joy, peace, and countless blessings. Wishing you and your loved ones happiness, prosperity, and togetherness. Enjoy the festivities and spread kindness! 🌙💙
#JIFAR CARRER
For those of you who find creativity challenging, try this
✨ Team up with someone who has similar goals or works on related projects.
Their ideas and experiences might open new doors and inspire fresh solutions.
Collaboration can increase your creativity and lead to amazing results—give it a try! 👊
#JIFAR TUTOR
@JifarSupport
Honoring and Memorizing this photo☺️😊
## JIFAR TUTOR:Unleash Your Potential, Embrace the JImma Aba Jfar Legacy
JIFAR TUTOR:Where History Inspires Your Future
> At JIFAR TUTOR, we're dedicated to bringing history to life, inspiring students to unlock their own potential and shape their own futures.
> Our Legacy
> * Student Spotlight Series: Hear from real students who are finding their own voices and shaping their own destinies, inspired by JImma Aba Jfar's example.
> * "Beyond the Textbook" Experiences: Explore local historical sites, connect with experts, and delve deeper into JImma Aba Jfar's legacy through real-world experiences.
> With JIFAR TUTOR, you'll:
> * Develop essential skills for success in the 21st century: critical thinking, communication, and problem-solving.
> * Discover your own leadership potential and find inspiration for creating positive change.
📝Visit Our channels: @JIFAR1
🛎Call 24/7':@JifarSupport 0953484398
#JIFAR TUTOR
#JIFAR TUTOR
New Job opening‼️
🎆We are Jifar Tutor🎆
✍️Place: Tshire
✍️Student: Grade 11
✍️Duration: 4 or 3 in a week
✍️Salary: monthly by Agreement
✍️#Females apply for this job
✍️ Subject All
📖We need punctual and who have excellent professional ethics and applicants for this position.
#Jifar HomeTutor #ጅፋር#ቤትለቤት(Online) #አስጠኚ
#በፈለጉን#ሁሉ#አለን! #
#የልጅዎ#እና#የርስዎ#ቀዳሚ#አጋር!
በዚህ ያናግሩን @JifarSupport
🎆 Jifar Tutor your choice🎆
ከታች ያለዉን የቴሌግራም ቻናላችን ይቀላቀሉ
👉@Jifar1
✅Job status - CLOSED‼️