Когда разрабатываете свой 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
📍 Mount Teide, Tenerife Island, Spain 🇪🇸
🌋 Mount Teide is located in the center of the largest of the Canary Islands - Tenerife. The mountain, which can be seen today from any point on the island of Tenerife, grew more than a hundred thousand years ago from the depths of the ancient stratovolcano Las Cañadas, the top of which once collapsed inward under the weight of the erupting lava.
This majestic peak, standing at 3,718 meters (12,198 feet), is the highest point in Spain and the third highest volcano in the world, rising from its base on the ocean floor. The surrounding Teide National Park boasts an otherworldly landscape of volcanic craters, lava fields, and unique flora and fauna. A cable car ride to the top offers breathtaking views of the island and the Atlantic Ocean beyond. 🌋🚠
#travel#adventure#canaryislands
🇪🇸🇮🇨Spain says over 1,000 migrants reached its Canary Islands in 3 days as more attempt deadly crossing
More than 1,000 migrants from sub-Saharan countries arrived in Spain's Canary Islands in 18 boats over the past three days, Spain's marine rescue service said on Monday.
The archipelago off northwest Africa has seen a surge in migrant arrivals in recent weeks as more people from West Africa attempt to get their, which is a dangerous trip.
Officials say 7,270 migrants arrived in January, about as many as in the first six months of 2023.
Most of the boats depart from Mauritania. Spanish Prime Minister Pedro Sánchez and European Commission President Ursula von der Leyen will visit the West African country on Thursday to encourage authorities to try to curtail the departures.
#Spain#CanaryIslands
@africaintel
Drone drops food for dogs trapped in La Palma by volcano lava
Several emaciated dogs lie curled up in and around a walled, ash-covered yard cut off by volcanic lava in the mountainous area of Todoque, on the Spanish island of La Palma, until a drone appears in the sky to drop packages with food and water.
#CanaryIslands#LaPalma#volcano#Spain#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Sunspots seen in Spain as geomagnetic storm expected
Sunspots were seen from Spain's Canary Islands as a geomagnetic storm was expected to reach the Earth.
#Sunspots#Spain#CanaryIslands#GeomagneticStorm#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Red-hot lava forces evacuations in Spain's La Palma
Over 700 residents on the Spanish island of La Palma were ordered to abandon their homes as lava advanced toward their neighborhoods.
#LaPalma#Spain#volcano#CanaryIslands#CumbreVieja#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
🐟 Rare Encounter with the “Sea Devil” near the Canary Islands!
For the first time in history, biologists managed to capture this mysterious deep-sea predator on video. Usually, only larvae or dead specimens are observed, as anglerfish live at extreme depths where almost no light reaches. But this time, the fish rose to the surface and appeared in front of the researchers’ camera — a truly unique observation for science!
#MarineLife#Anglerfish#DeepSeaMysteries#CanaryIslands☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube.
Lava spews from La Palma volcano
The Cumbre Vieja volcano on Spain's La Palma island continues to spew lava and smoke.
#Volcano#LaPalma#Spain#Lava#CanaryIslands#CumbreVieja#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Volunteers take in La Palma's homeless pets
This makeshift shelter in La Palma, Spain, is housing hundreds of homeless pets after their owners were forced to flee from the Cumbre Vieja volcano.
#Volcano#LaPalma#Spain#Lava#CanaryIslands#CumbreVieja#HomelessPets#Pets#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖