Когда разрабатываете свой 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
#WellnessWednesday: Your health is your greatest asset.
Regular physical activities strengthens your heart, boosts your mood, improves productivity, and helps prevent chronic diseases.
✅ 30 minutes of exercise daily can make a big difference.
Make movement a priority today. Stay active. Stay healthy.
#WellnessWednesday#HealthyLiving#NCDCNigeria
#WellnessWednesday: Your health is your greatest wealth.
Stay active
➡️Drink Enough water
➡️Reduce sugar intake
➡️Aim for at least 7–8 hours of sleep daily
➡️Eat more fruits and vegetables.
Small healthy habits every day leads to a stronger, happier you.!
#WellnessWednesday#HealthyLiving#NCDCNigeria
#WellnessWednesday
Your wellness is your greatest achievement ✅
Eat well, Move often, Get enough rest and Protect your Peace !
Consistency builds a healthier you!!!
#WellnessWednesday#HealthyLiving#NCDCNigeria
#WellnessWednesday
⚡️Maintaining good health starts with simple, consistent habits.
Regular exercise, adequate rest, hydration, and a balanced diet help strengthen both body and mind.☑️
Make wellness a daily priority, small actions lead to lasting health.👍
#WellnessWednesday#HealthyLiving#NCDCNigeria
#WellnessWednesday: Your health journey starts with you!
💦Water is essential for your body and mind to function at their best.
Stay hydrated throughout the day and aim for at least 8 cups of water per day.✅
Small sips, big difference!
#HealthyLiving#WellnessWednesday#NCDCNigeria
#WellnessWednesday: Sleep Smarter, Wake Brighter
Good sleep is just as important as healthy eating and exercise.
Prioritise rest, aim at least 8hours of quality sleep and create a calm routine for a healthier you. 💤
#HealthyLiving#WellnessWednesday#NCDCNigeria
#WellnessWednesday: The Power of Good Hygiene
Good hygiene is your first line of defense against infections and diseases!
✅ Wash your hands often with soap under clean running water
✅ Keep your surroundings tidy
✅ Cover your mouth when you cough or sneeze
✅ Don’t share personal items
✅ Practice proper food hygiene
Small actions can make a big difference in protecting your health ✔️
Stay Healthy, Stay Safe!
#HealthyLiving#WellnessWednesday#NCDCNigeria
#WellnessWednesday:
Take time today to recharge👌
✨Your health is your greatest investment, make choices that helps you feel stronger, calmer, and more balanced every day.
#HealthyLiving#WellnessWednesday#NCDCNigeria
#WellnessWednesday: Fuel your body, calm your mind 🌱
True wellness goes beyond just eating right or exercising — it’s about finding harmony between your body and your mind. When you give your body the right nutrients, plenty of water, rest, and movement, you’re not only building strength but also creating the foundation for mental clarity and peace. 🙌
🧘🏾♀️A calm mind reduces stress, sharpens focus, and helps you show up fully in every area of life.
#HealthyLiving
#WellnessWednesday#NCDCNigeria
#WellnessWednesday: Eat better, Live better!
👉 Eating healthy isn’t about restriction, it’s about making smarter choices every day- choosing the right foods that helps fuel your body and mind✔️
Here are some tips on how to eat healthy👇🏿
➡️Eat the rainbow: Fill your plate with colorful fruits and veggies. Each color brings unique nutrients.
➡️Go whole, not processed: 🌾 Whole grains, beans, nuts, and fresh produce keep your energy steady.
➡️Healthy fats matter : Avocados, olive oil, and fish support your heart and brain.
➡️Stay hydrated: Water helps your body absorb all the goodness from food.
➡️Mindful eating: Slow down, chew well, and enjoy every bite.
✨ Eat smart, Stay strong, Live well!
#WellnessWednesday#HealthyLiving#NCDCNigeria
#WellnessWednesday: Simple Stress management Tips
Small daily habits can make a big difference for your health! 🌿
✅ Eat a balanced diet rich in fruits & vegetables
💧 Stay hydrated
✍️ Work smarter not harder
🏃♀️ Move your body daily, even with light exercise
😴 Prioritize 7–9 hours of quality sleep
🧠 Take time to relax, rest your mind and manage stress
Your health is an investment — care for it today for a stronger tomorrow. 💪
#WellnessWednesday#HealthyLiving#NCDCNigeria
#WellnessWednesday: Your Health, Your Priority!
Wellness isn’t a one-time goal, it’s a lifestyle and a continuous journey. Each day gives us an opportunity to make small but powerful choices that strengthen our body, calm our mind, and nourish our soul. 🧘♀️
Prioritize your health — eat nourishing meals, stay active, rest well and protect your mental health 🧠.
✅ Stay consistent
✅ Listen to your body
✅ Make your health a priority
#WellnessWednesday#HealthyLiving#StaySafe#NCDCNigeria