Когда разрабатываете свой 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
🚨🇺🇸MICROSOFT AI INVESTMENTS TRIGGER MASSIVE TECH SELLOFF FEARS
🔹 MSFT crashes 15% YTD to $410 after revealing $37.5B AI capex spending — Wall Street panicking over return on investment timeline 💰📉
🔹 Tesla faces March 9 NHTSA compliance deadline for 2.88M FSD vehicles — potential $139M penalty sparks 2% pre-market drop to $388 🚗⚡
🔹 Software sector hemorrhages $800B as S&P Software Index plunges 13% in February — biggest tech rotation since 2002 dot-com crash 💸
Silicon Valley's AI gold rush hitting reality wall — investors fleeing to consumer staples as tech's worst quarter since 2008 unfolds 🤔💥
#TechStocks#USNews
@america
📈Volatility Log: Skew Says Tech Stocks and Europe Rates Aren't Done
Despite seemingly calm spot markets, the volatility log reveals persistent hedging demand driven by intertwining macro catalysts including key tech stocks and European inflation trends. We examine...
🔗Read Full Analysis
🎯 SPECIAL OFFER: 15% OFF
💸 Coupon Code: salenow15%
🚀 Upgrade to premium signals → https://markets.fxpremiere.com/en/signals?utm_source=telegram
📰 Stay ahead — get breaking financial news & analysis at https://markets.fxpremiere.com/en?utm_source=telegram
#Volatility#TechStocks#InterestRates
🚀 Hong Kong Stocks Open Lower as Tech Shares Decline
Hong Kong stocks opened lower today, with the Hang Seng Index dropping 0.71% and the Hang Seng Tech Index falling 0.69%. According to Jin10, technology stocks led the decline, with Baidu (09888.HK) down over 3% and NetEase-S (09999.HK) falling more than 2%.
#HongKongStocks#HangSengIndex#HangSengTechIndex#TechStocks#Baidu#NetEase
🚀 STOCKS | Hong Kong's Hang Seng Index Retreats After Previous Surge
On April 9, Hong Kong's Hang Seng Index experienced a pullback following a significant rise of nearly 800 points the previous day. According to Jin10, the index opened over 100 points lower in the morning and briefly fell more than 200 points to reach 25,653.63 points before recovering slightly. By midday, the Hang Seng Index closed down 0.35% at 25,803.12 points, while the Hang Seng Tech Index fell 1.26% to 4,861.39 points. The total market turnover for the Hang Seng Index reached HKD 126.652 billion.
In terms of sector performance, optical communication and computing infrastructure stocks led gains, while the innovative drug concept saw a brief surge in early trading. However, most technology stocks underwent a correction, with real estate and gold stocks experiencing notable declines. Among individual stocks, Yangtze Optical Fibre and Cable Joint Stock Limited Company (06869.HK) rose 3.2%, WuXi AppTec Co., Ltd. (02359.HK) increased by 3.53%, Kingdee International Software Group Company Limited (00268.HK) fell 5.49%, Kuaishou Technology (01024.HK) dropped 3.55%, and Longfor Group Holdings Limited (00960.HK) decreased by 4.07%.
#HangSengIndex#HongKongStocks#StockMarket#TechStocks#RealEstate#Gold#MarketPullback#Trading#Investment
🚀 Lumentum Holdings Sees 132% Return Amid Nvidia's $2 Billion Investment
Lumentum Holdings has experienced a remarkable 132% return this year, transforming a $1,000 investment in January into $2,320 by April. According to NS3.AI, this impressive rally is attributed to Nvidia's substantial $2 billion acquisition of ultra-high-power lasers and capacity rights for next-generation optical interconnects. The strategic move by Nvidia has significantly boosted investor confidence in Lumentum Holdings, driving its stock performance upward.
#LumentumHoldings#Nvidia#Investment#StockMarket#TechStocks#OpticalInterconnects#InvestorConfidence#HighReturn
Exodus Debuts on NYSE with 36% Gain
Exodus, a developer of non-custodial software, made its debut on the New York Stock Exchange (NYSE) under the ticker EXOD. In its first trading session, shares surged 36%, bringing the company's market capitalization to $1.4 billion. For more details, visit ForkLog.
#Exodus#NYSE#IPO#StockMarket#Investing#Growth#TechStocks#FinancialNews#Blockchain#Software#NonCustodial#MarketCapitalization#Trading#WallStreet
DeepSeek AI Disrupts Tech and Crypto Markets
DeepSeek, a Chinese AI startup, launched its DeepSeek-R1 model, rivaling OpenAI's offerings but at significantly lower costs. The buzz around DeepSeek has led to a $1 trillion drop in US tech stocks, with Nvidia shares tumbling nearly 10%. Experts caution against hasty conclusions regarding the market reaction. Amidst this, investment director Michael van de Poppe advises Ethereum investors to stick to long-term strategies, predicting positive growth for Ethereum and Solana in 2025 due to lower interest rates and geopolitical instability. Read more about the implications of DeepSeek's emergence on the tech landscape here.
#AI#DeepSeek#Crypto#Ethereum#Solana#TechStocks#Nvidia#MarketCrash#Investing#Finance#Web3#MachineLearning#ArtificialIntelligence#Startups#China#Innovation#Stocks#HedgeFund#DeFi#Trends#MarketTrends