Когда разрабатываете свой 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
Йога на закате☀️🤸🏼♀️🧘🏼♀️✨💙
@huvafenfushi_maldives это лучшее место для покоя, гармонии, единения с собой и природой, энергетических практик, поддержания формы и ее содержания, поисков баланса и настроя на трудовые городские будни✨ Здесь нет счета времени, у всех прохожих добрые приветливые лица,теплые, мягкие ладоши при рукопожатии, тут жарят рыбу,обваляв ее в кукурузной муке, приготовливая на отдельной сковородке с кривой серповидной ручкой , маслины с сыром и большой цветок бузины в хлебных крошках. А после подают кофе с мастикой, розовым рахат-лукумом и пирогом из фиников.. И ещё можно повторить целебные слова, которым меня тут научили .. Ho’oponopono – The Magical Words 🤍
‘ I am sorry
Please forgive me
I love you
Thank you’
Всем спасибо за сегодня ,здесь и сейчас💙🧜🏻♀️🐚💫
#мира#heavenonearth#mermaidlife#vacances#topstretching#yoga#bluelagoon#maldives#huvafenfushi#mira#harmony#balance#hoponopono#energy #🧘🏼♀️ #🤍#bestvacations
Lete lete Kamao Lakho 💸💸💵💵😨😨😨
#funnyreels#funnyvlog#funny#comedyreels#comedy#companygarden#explorepage#explore#diwalioffer#diwali#jobs#job#offer#vacancy#vacances#visa#freejob#howtoearnmoney#money#boys#theboys#shamimup70#uttarpradesh#up70#viral#trending
Можно просто лопнуть от восторга..🥹
Всем самого доброго утра☀️
Heaven on Earth..🩵
#sun#sunvibes#sunrise#moodoftheday#goodvibes#goodmorning#barosmaldives#blissfulbaros#mirasbaros#maldives#reels#video#heavenonearth#harmony#purelove#vacation#vacances#happy#mothernature#planetearth#ocean#mermaid
The more time we spend with Mother Nature the more we fall in love..
….I’m so in love..
..Thank you God for another most amazing day,for the leaping greenly spirits of trees ,and for the blue dream of sky and for everything which is natural ,which is infinite…
…which is yes..
Thank you @velassarumaldives for this magical experience 💚✨🙏🏻☀️
#positivevibes#velassarumaldives#maldives#maldivesislands#summer #2024 #haveaniceday#moodoftheday#newpost#photooftheday#junglebook#ocean#mothernature#planetearth#vacation#vacances#mira#доброеутро#всемотличногонастроения#sun#purelove#sunvibes#mom#daughter#indianocean
Ahoy, me Hearties!
Do you know what is the secret of @velassarumaldives ??
It gives you wings !🩵
Fair wind to everyone yo ho ho😜🫶🏻
#velassarumaldives#moodoftheday#video#photooftheday#heavenonearth#reels#ladysailor#piratelife#purelove#sunvibes#summer #2024 #maldives#maldivesislands#vacation#vacances#smile#haveaniceday#доброеутро#всемотличногонастроения#отпуск#sun#морячка#mira#actress#actrice#positivevibes#ahoy
At a place where you learn to coalesce with all the unfamiliar time-space-school-of-fish-cloud formation flows ,outbursts and stillnesses. I keep chanting ,underwater while studying coral reefs ..Complete balance and harmony with @barosmaldives in The Serenity Spa 🧘🏻♀️🕉️☯️💚
#goodmorning#barosmaldives#доброеутро#mothernature#moodoftheday#post#purelove#heavenonearth#vacation#vacances#mira#actress#summer #2024 #summervibes#resort#blissfulbaros#maldivesislands#maldives#haveaniceday#photooftheday#model#sun#harmony#energy#spa#spaday#serenityspa#planetearth
I’m back!❤️🔥
Luxury undressed by @velassarumaldives🧜🏻♀️🫶🏻
The local beach,lagoon,coral reefs and marine flora and fauna have an extraordinary beauty that cannot be expressed in words.This is one of the most amazing places you would like to visit in your life.It is the epitome of beauty with white sand and clear water.This is Mother Nature’s best masterpiece,every day she mixes all the colors of the sky and the ocean,and you can’t figure out whether the sky is eating the ocean or the ocean is eating the sky.Watching,enjoying,filling up..
#velassarumaldives#nextstop#resort#luxury#maldives#maldivesislands#vacation#vacances#sun#summer #2024 #photooftheday#moodoftheday#beachlife#sunvibes#positivevibes#purelove#heavenonearth#mira#actress#mothernature#planetearth#velassaru#magic#miracle#haveaniceday#доброеутро#отпуск#всемотличногонастроения#лето
Good morning!☀️
Wow,everyone here is so-so friendly🥰
Today’s photo shoot area is ready for all ladies and gentlemen 😂😜 A long-legged bird, Josephine, awaits all guests 🫶🏻
Location: Dive Center @velassarumaldives🧜🏻♀️😉
Take beautiful photos, create your best memories, enjoy the views, walk, dance, smile, be happy - this is your life!
The mantra of the day…Inhale the future.Exhale the past!🩵☀️🪽
My best photographer-Mom Lora @nuzza_ka😍
#velassarumaldives#maldives#maldivesislands#ocean#vacation#vacances#holidays#photooftheday#moodoftheday#latina#sun#sunvibes#positivevibes#purelove#heavenonearth#jungle#resort#summer #2024 #smile#harmony#relax#доброеутро#всемотличногонастроения#отпуск#longlonglegs#legs#model#actress#mira
Добрались ☀️
Всем каникул!Всем Солнца!Всем счастья!Всем самых лучших настроений!Всем крепкой любви!Впереди только самые летние,заразительно-восхитительные,приносящие радость фото и видео с волшебным эффектом-кто посмотрит,тот тоже обязательно поедет в свой самый лучший отпуск🫶🏻!Рубрика #mirasbaros coming soon😉
Итак остановка No 1 🥁🥁🥁
BAROS MALDIVES @barosmaldives✨
Уже влюблена,по глазам всё понятно🩵🐬
P.S.- спасибо @sashoulik Сашенька и Вероника @veronica_karpova🫶🏻 Обнимаю обнимаю -обнимаю!!!
#barosmaldives#blissfulbaros#vacation#maldives#holidays#sea#ocean#mira#отпуск#каникулы#лето#summer#summervibes#moodoftheday#photooftheday#actress#actrice#model#behappy#heavenonearth#purelove#sun#balance#harmony#sport#happiness#vacances#ladysailor#sailor
Our magical kingdom where the dreams of relaxation come true🫶🏻Thank you for our private haven @barosmaldives🤲🏻🩵
P.S.-Вариация афиши к кинофильму «Мальдивы НЕ подождут» 2 😂🩵🐬
#maldives#maldivesislands#barosmaldives#mirasbaros#vacation#sun#sunvibes#vacances#holidays#positivity#private#privacy#heavenonearth#ocean#blue#resort#luxury#energy#purelove#balance#harmony#photooftheday#moodoftheday#actress#actrice#model#haveaniceday#всемхорошихвыходных#суббота#saturday