Когда разрабатываете свой 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
#DGB/USDT analysis :
#DGB is expected to retest the 200 EMA before continuing its bearish trend. This creates a potential buying opportunity on lower time frames (LTF), and the current level is a good point for long trades.
TF : 4H
Entry : $0.00865
Target : $0.00970
SL : $0.00797
#DGB/USDT analysis :
#DGB is currently in a downtrend, consistently making new lows while trading below the 200 EMA. The price is now showing a retracement towards the 200 EMA and the resistance zone. It is expected to reverse and continue its bearish momentum. It is recommended to wait for the price to retest this zone and demonstrate rejection before considering a short entry.
TF : 1D
Entry : $0.00703
Target : $0.00541
SL : $0.00814
#DGB/USDT analysis :
#DGB has broken the support levels and has retested the zone, which is now acting as resistance for the price. The price is expected to decline from this level and test the previous swing low.
TF : 4H
Entry : $0.00662
Target : $0.00634
SL : $0.00681
#DGB/USDT analysis -
The current price movement of #DGB shows a rejection from the resistance zone after establishing a lower low. There is an anticipation of further decline from this point with a potential retest of the previous low. To effectively manage risk, it is advisable to set a stop loss above the rejection zone.
TF : 1h
Entry : $0.00716
Target : $0.00616
SL : $0.00757
#DGB👀
The second chart fully and automatically generated by our algorithm 🤖
All drawings are based on only mathematical values and calculations instead of emotions.
Interested? Check out www.coinlegs.com
#DGB hit 34 today 🔼
Trade opened on 24 March ✨
In both spot n future
Join team @CryptoProfitCoach🔝
⭐⭐ Lifetime Membership opened for a limited time⭐👈👇👇
🟥Multiply your wealth into multiple folds and Get Unique opportunity to trade with @CryptoProfitCoach
✨Buy when he buy sell when he sell...Know what Gem he holding✨
Join team @CryptoProfitCoach🟥
for mega gains and multiply your wealth
✅ Get personalized attention in every trade
✅More trades and Mega profits.
✨ Inside info/Secret info of Coin
✅No.1 Pump Tracking Services.
✅ High End Profit Targets
✅ 24x7 Support in all trades
✅ Get Entry n High end profit Exit with Team in every trade
✨Discounted price -500$ for a year with 24x7 chat support ✅
✨Today's decision can change your tommorrow✨
https://forms.gle/U519Ye8sCmvVE2Pv9
🟥Click here 👆👆✨✨