Когда разрабатываете свой 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
#Greenland🇬🇱
Eternal ice 🧊 Would you like to visit here?
About 80% of the territory of Greenland is covered with an ice shield, which is the second largest in the world after Antarctica. The ice in some places reaches a thickness of up to 3 km.
Greenland cuisine is based on the gifts of nature: fish, seafood, venison and dishes from marine mammals. For example, "Suasat" - sewen soup - is considered a traditional dish.
Отвлечемся на секунду от новостей автопрома и поговорим чуть о том, что в мире нет стабильности. Суматошный нестабильный эксцентричный президент США хочет заграбастать Гренландию.
В одном из своих интервью он сказал, что армия Гренландии состоит из двух собачьих упряжек. Гордые жители создали шедевральный ии-шный ролик (точно пару дней потратили) в котором продемонстрировали свои военные возможности. У них есть собаки, моржи и пингвины (почему-то в форме образца СССР).
Что мы вообще думаем об этой ситуации. Заберет или не заберет?
Заберет - 👎
Не заберет - 👍
Вообще это какая то дичь - 🥴
Ролик огонь - ❤️
#greenland
#GREENLAND RESULT
—————————
PEAK: 1,109%
If you think that was a great move, you haven't seen what we have planned for our next launch...
After giving it to you guys, we pushed #GREENLAND over 1,100% in a matter of less than an hour, destroying our target and guaranteeing the biggest profits for our members.
Trump is about to move the global economy again, and we're about to have the biggest 100x opportunity we've had in years. We're just getting started
Stay tuned.
👣 The iceberg's breath in northeast
Greenland. Silence and icy expanses where every breath feels like nature itself.
📏
📏
📏
📏
📏
📏
📏
📏
#Greenland | @voyage
👣 The iceberg's breath in northeast Greenland. Silence and icy expanses where every breath feels like nature itself.
📏
📏
📏
📏
📏
📏
📏
📏
#Greenland🇬🇱@voyage
#GREENLAND RESULT
—————————
PEAK: 1,109%
If you think that was a great move, you haven't seen what we have planned for our next launch...
After giving it to you guys, we pushed #GREENLAND over 1,100% destroying our target and guaranteeing the biggest profits for our members.
Trump is about to move the global economy again, and we're about to have the biggest 100x opportunity we've had in years. We're just getting started
Stay tuned.
👣 The iceberg's breath in northeast Greenland. Silence and icy expanses where every breath feels like nature itself.
📏
📏
📏
📏
📏
📏
📏
📏
#Greenland🇬🇱@voyage
The United States abandoned the idea of seizing Greenland due to the threat of impeachment to Trump, - Reuters
#Trump#Greenland
👂More on Trump's Ear ⚠️
The world would be a “better, more secure place” if America took over Greenland, Nigel Farage said at Davos, while insisting that he still believed in the sovereignty of nation states.
During a panel at the World Economic Forum’s “America House” in the Swiss ski resort on Wednesday, the Reform UK leader said he had “no doubt” that the world would be safer if a “strong America” was in Greenland “because of the geopolitics of the high north, because of the retreating ice caps and because of the continued expansionism of Russian icebreakers, of Chinese investmen
#Trump#Greenland
👂More on Trump's Ear ⚠️
The United States needs Greenland for national security reasons, Trump said.
According to the US president, the island is important for the creation of the Golden dome system. And NATO is supposed to pave the way for America to get Greenland.
#Trump#Greenland
👂More on Trump's Ear ⚠️