Когда разрабатываете свой 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
🇺🇸#LosAngeles. Wild teens ransack Chevron store in Lincoln Heights in broad daylight.
Another SoCal store is taken over by rampaging teens racksacking aisles, grabbing whatever they can. This time, a Lincoln Heights Chevron station is hit. The frustrated store managers who want police to do more to stop the takeovers.
Follow us -> LiveLeak
Please do not curse the victims of the American fires. There are many innocent civilians and pro-Palestinian people. Those elites had already fled before the fires came.
#LosAngeles
This is absolutely disgusting and heartbreaking.
Homeless addicts on Skid Row in LA are using innocent dogs to test their drugs for fentanyl. These poor animals are being fed deadly substances, abused, neglected, sold for drugs, and thrown away like trash.
Volunteers from Starts With One Today are risking their lives to rescue these dogs with zero support from the city.
How has Mayor Karen Bass and LA leadership let this horror continue? Animals are suffering and dying in plain sight while officials do nothing.
This is pure cruelty. Where is the outrage? Where is the action?
#SaveSkidRowDogs#AnimalAbuse#LosAngeles
🔹👉🏻@SherriTenpenny
PERFECT RING FORMED OVER LOS ANGELES
This appeared high above L.A. just after dusk.
A bright linear trail stretched across the sky — and around it, a smooth circular arc expanded and held its shape.
The symmetry is what stands out.
A straight line through the center.
A clean curve wrapping around it.
It lingered long enough for people across the city to stop and stare.
Los Angeles, California.
Did you catch this from where you are?
MrMBB333
👇 Drop your city.
#MrMBB333#SkyWatch#LosAngeles
#Wildfires ravage #California, leaving 5 people dead and over 27,000 acres burned. #LosAngeles Authorities warned casualties may rise as the fires remain uncontained.
USA Major League Soccer🇺🇸
2026-04-19 23:00 UTC
Los Angeles FC vs. San Jose Earthquakes
Predicted outcome: Los Angeles FC❌
Predicted score: 2:1
Actual: San Jose Earthquakes 1:4
#LosAngeles#SanJoseEarthquakes
#Football#USAMLS
As #LosAngeles burns and #firefighters face a severe water crisis, criticism is mounting against #billionaires Stewart and Lynda #Resnick, whose $13B agricultural empire consumes more water than LA and SF combined.
#PalisadesWildFire
USA Major League Soccer🇺🇸
2026-05-10 20:30 UTC
New York City FC vs. Columbus Crew
Predicted outcome: New York City FC✅
Predicted score: 3:2
Actual: New York City FC 3:0
#NewYorkCity#ColumbusCrew
2026-05-10 23:00 UTC
Minnesota United FC vs. Austin
Predicted outcome: Minnesota United FC❌
Predicted score: 2:1
Actual: Draw 2:2
#MinnesotaUnited#Austin
2026-05-11 01:00 UTC
Los Angeles FC vs. Houston Dynamo
Predicted outcome: Los Angeles FC❌
Predicted score: 2:1
Actual: Houston Dynamo 1:4
#LosAngeles#HoustonDynamo
#Football#USAMLS