Когда разрабатываете свой 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
🇮🇷 Breaking: University protests flare up across Iran
New student protests erupted at major Iranian universities as the new term began, with demonstrators honouring victims of last month’s deadly crackdown. Clashes were reported in Tehran, with chants targeting Supreme Leader Ali Khamenei and reviving the “Woman, Life, Freedom” movement.
The unrest comes amid rising geopolitical tensions, as the U.S. boosts its regional military presence while nuclear talks with Tehran remain unresolved. #News#Iran#University
「💻」#university#studying_tips
new semester, better me 📚🦪.
Yesterday I did a lot of stuff including unpacking and setting up my room for the semester.
Of course I will redecorate it, however I shouldn’t forget that this room is for only one semester
✨
Inshallah will go to study away
😻
~🐈~
↬@jastm1🌊
「💻」#university#studying_tips
❤️Some college x School inspo
✨A new chapter is here!✨
Are you ready for school/college? ✨
This is the perfect time to set new ambitions and new goals. A chance to start fresh, grow, and chase the best version of yourself. 🌱
Don’t be shy, step forward with confidence, give it your best, and make this year unforgettable.💗🫶
~🐈~
↬@jastm1🌊
「💻」#university#studying_tips
Checklist of things to pack for UNIVERSITY🥳!
Most of you might be overwhelmed with the amount of things to do, but don't worry you've got this 💪.
Save not to loose!
~🐈~
↬@jastm1🌊
https://www.coursera.org/specializations/data-science-python?utm_medium=email&utm_source=marketing&utm_campaign=2QBGEJZREeajEnVsu251ig
The 5 courses in this #University of #Michigan specialization introduce learners to data science through the python programming language. This skills-based specialization is intended for learners who have basic a python or programming background, and want to apply statistical, machine learning, information visualization, and text analysis techniques to gain new insight into their data.
Introduction to Data Science with Python (course 1), Applied Plotting, Charting & Data Representation in Python (course 2), and Applied Machine Learning in Python (course 3) should be taken in order and prior to any other course in the specialization. After completing those, courses 4 and 5 can be taken in any order. All 5 are required to earn a certificate.
Bizning faxriy oqituvchimiz Sultanov Ruslan Rustamovich
➖➖➖➖
Наш почётный учитель Султанов Руслан Рустамович
#tiue#university#университет
Telegram | Instagram | Website
Congratulations Class of 2027! Welcome to New Uzbekistan University! 🎉
#NewUU2027#NewUzbekistanUniversity#University
Check out the full video on our YouTube!
Best Regards,
NewUU Student Council
Telegarm | Instagram
🇰🇷Janubiy Koreya ta’lim tashkilotlari bilan hamkorlik aloqalari mustahkamlanmoqda
🇺🇿Batafsil
___
Strengthening cooperation with South Korean educational organizations
🇬🇧Eng
___
Укрепление сотрудничества с Южно-Корейскими образовательными организациями
🇷🇺Ru
#GraduateSchool#Soonchunhyang#University#Cooperation
Web-site | Telegram | Facebook | Instagram
Handong Global universiteti bilan hamkorlikni yangi bosqichlari
🇺🇿Batafsil
___
New Stages of Collaboration with Handong Global University
🇬🇧Eng
___
Новые этапы сотрудничества с Глобальным университетом Хандонг
🇷🇺Ru
#GraduateSchool#Handong#Collaboration#University
Web-site | Telegram | Facebook | Instagram