Когда разрабатываете свой 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
Macron Sounds Brave on Israel, Frugal at Home
Emmanuel Macron condemned Israel over the blocked Palm Sunday procession in Jerusalem, calling freedom of worship something that must be guaranteed for all religions.
Fair enough — except this is the same French president whose government is now offering only tightly targeted fuel aid because, as France’s central bank put it, there is “no more money” for broad subsidies.
That’s the modern European posture in miniature: moral thunder abroad, budget discipline at home.
Macron can scold Israel for trampling holy sites, but when French drivers and businesses get squeezed by the oil shock, Paris reaches for a scalpel, not a blanket. The principles are grand; the compensation is minimal.
And that tension is the point. The Middle East crisis has pushed fuel prices higher across Europe, but France’s answer has been cautious, targeted relief rather than the old-school political sugar rush of big subsidies.
So Macron gets to play the global conscience while his own finance people remind everyone that righteousness does not pay the diesel bill.
#Macron#France#Israel#Jerusalem#fuelprices#MiddleEast#politics
📱American Оbserver - Stay up to date on all important events
🇺🇸
🚢Рекордные премии на бункер вынуждают суда искать топливо в азиатских хабах.
Резкий рост цен на морское топливо на фоне конфликта на Ближнем Востоке привёл к серьёзным сбоям в бункеровке судов в крупнейших азиатских портах. По данным участников рынка, стоимость топлива выросла более чем в два раза по сравнению с уровнем до начала конфликта.
В крупнейшем мировом бункеровочном хабеСингапуре цена низкосернистого топлива превысила $1 000 за тонну, а премии на спотовом рынке достигли рекордных уровней — значительно выше отметки $200 к базовым котировкам.
Суда всё чаще сталкиваются с задержками при бункеровке, что может привести к росту загруженности портов Сингапура, Шанхая и Нинбо-Чжоушань.
Перенаправление судов из-за ограничений транзита через Ормузский пролив также увеличивает поток трафика в азиатские порты.
По оценке аналитиков, многие поставщики переходят на спотовые продажи, избегая долгосрочных контрактов из-за высокой волатильности цен.
Дополнительное давление на рынок создаёт сокращение поставок топочного топлива из стран Ближнего Востока.
Для судоходной отрасли это означает рост операционных затрат, увеличение времени ожидания в портах и дополнительное давление на фрахтовые ставки.
📌Linerlytica — аналитическая компания в сфере морской логистики и контейнерных перевозок, специализирующаяся на анализе глобальных торговых потоков и портовой статистики. Компания является частной и принадлежит основателям и инвесторам.
#Bunkering#FuelPrices#SingaporePort#ShippingCosts#MaritimeTrade
🚀 Poland's Central Bank Highlights CPI Risks from Fuel Price Policies
Poland's central bank has identified fiscal policies and regulations related to fuel prices as ongoing risks to the Consumer Price Index (CPI). According to Jin10, these factors continue to pose challenges to the country's inflation outlook. The central bank's assessment underscores the importance of monitoring fuel-related policies as they can significantly impact inflation rates. Policymakers are urged to consider these risks in their economic strategies to ensure stability in the CPI.
#Poland#CentralBank#CPI#FuelPrices#Inflation#FiscalPolicies#EconomicStability#InflationRisks
🚀 Middle East Conflict Could Severely Impact Australia's Economy, Expert Warns
Calculations and analyses are currently underway regarding the potential impact of the ongoing Middle East conflict on Australia's fuel prices and economic growth. According to Jin10, David Rumbens, a partner at Deloitte Access Economics, has stated that the worst-case scenario would severely affect Australia. A prolonged conflict could drive oil prices up to $175 per barrel, with inflation rates reaching 7.5% by the end of the year. The ultimate outcome could see Australia's unemployment rate rise to 6.8%, while the GDP growth rate could decline by 2.8%. Notably, none of the proposed scenarios indicate an unemployment rate below 5.0%.
#MiddleEastConflict#AustraliaEconomy#FuelPrices#EconomicGrowth#Inflation#Unemployment#GDPGrowth#OilPrices#DavidRumbens#DeloitteAccessEconomics
🚀 Macquarie: Southeast Asia Fuel Prices Surge Amid Iran Conflict
Macquarie stated in a stock research report on April 9 that fuel prices in Southeast Asia have significantly increased and are unlikely to return to pre-Iran conflict levels in the short term. According to Jin10, the firm remains optimistic about energy-related industries, including alternatives like crude palm oil, while advising against non-essential consumer goods, hotels, and leisure sectors. Macquarie noted that after a substantial rise in oil prices, it typically takes about six months for consumer inflation to show a significant increase. The report also mentioned that energy subsidies in Malaysia and Indonesia might temporarily mitigate the negative impact on consumers.
#SoutheastAsia#FuelPrices#IranConflict#Macquarie#EnergyIndustries#CrudePalmOil#ConsumerInflation#OilPrices#EnergySubsidies#Malaysia#Indonesia