Когда разрабатываете свой 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
To encourage diners to keep the tables clean at public dining places, NEA will complement existing educational efforts with enforcement. The 3-month advisory period begins from 1 Jun 2021, and enforcement will commence at hawker centres from 1 Sep 2021. More at https://go.gov.sg/nea-news-mandatory-to-clear-tables#ClearYourTable
Our Wordle of the day – did you manage to get yours right today?
Don’t forget to clear your table after eating at our hawker centres, coffeeshops and food courts.
P.S. You don’t have to clean your table, as cleaners will be cleaning and sanitising tables.
#ClearYourTable#ReturnYourTray#BinUsedTissues
Doesn't it feel shiok to have a clean table to enjoy your favourite hawker food? When you're done, don't forget to #ReturnYourTray and #BinUsedTissues so that fellow diners can feel the same shiok.
#ClearYourTable
As we begin dining out again, remember to practise good hygiene, to protect ourselves, other diners, and our cleaners – many of whom are seniors. When you’re done eating, remember to #ClearYourTable, #ReturnYourTray and #BinUsedTissues.
Leaving litter on tables at our public dining places is an offence. NEA is taking an advisory approach in the lead-up to 1 Sep 2021, after which enforcement action will be taken against patrons who fail to heed our officers’ advice. www.nea.gov.sg/media/news/advisories/index/clear-table-as-dine-in-resumes
As dine-in gradually resumes from today, let’s do our part in keeping our favourite public dining spaces and our cleaners safe by remembering to #ReturnYourTray, #ClearYourTable and #BinUsedTissues. If we simply get up and walk away, the dirty crockery and food remnants can attract unwanted pests. Our used tissues also carry germs that pose potential health risks to cleaners and other diners.
Expectation: All ready to order my beloved hawker delights 😍
Reality: Oh no, the previous diners did not clear their tables 🥴
Let's play our part in keeping #OurHawkerCentres clean, by clearing our used tray and crockery.
Details and FAQs here: www.nea.gov.sg/clean-tables
#ClearYourTable#ReturnYourTray#BinUsedTissues
Here’s what the same area at Queen’s St Hawker Centre looks like in 2016 and 2021. What a dramatic transformation we've seen lately! Better tray return infrastructure and a new cleaning workflow are initiatives we’ve adopted to ensure cleaner and safer public dining places.
Diners and cleaners at #OurHawkerCentres have played a great part in making this system work. So next time you’re dining at #OurHawkerCentres, be part of that change and #ClearYourTable, #ReturnYourTray and #BinUsedTissues to keep our public dining places clean and safe for everyone. Thank You - to our cleaners, fellow diners and all of you, for supporting us! ❤️
#DidYouKnow that our cleaners do more than just clear our tables? They also need to sanitise tables, clear the tray/crockery return stations, and return clean crockery to the stalls.
Let’s do our part to help our cleaners! #ReturnYourTray#ClearYourTable#BinUsedTissues
Want a clean table ASAP? So do your fellow diners. Help #ReturnYourTray so that others get to eat their hawker food faves before they get cold. 🥺#ClearYourTable#ThankYouCleaners
Savour the perfect blend of sweet, spicy, and tangy tastes of Rojak - Singapore's iconic hawker dish! 🥗🍍🥒
Whether you love it with a generous serving of thick savoury sauce or prefer it with a spicy kick, Rojak is certainly a good treat for our taste buds. P.S. Don’t forget to return your used tray and crockery after enjoying your meal!
#OurHawkerCentres#OurHawkerCulture#ClearYourTable#ReturnYourTray#BinUsedTissues
Extending our heartfelt appreciation to diners who have been returning their used trays and crockery. This small act goes a long way towards ensuring a pleasant dining experience for everyone.
Let's continue to keep #OurHawkerCentres clean this new year!
Details and #FAQs here: www.nea.gov.sg/clean-tables
#ClearYourTable#ReturnYourTray#BinUsedTissues
Yes, the revised cleaning workflow aims to ensure that the tray and crockery return stations are cleared, cleaned and sanitised quickly and efficiently, to prevent pest nuisance.
As our cleaners need time to adjust to the new workflow and manage their different tasks, do look for alternative tray and crockery return stations if the one nearest to you is full. Let’s continue to keep #OurHawkerCentres clean and safe. #ClearYourTable#ReturnYourTray#BinUsedTissues
More #FAQs at www.nea.gov.sg/clean-tables