Когда разрабатываете свой 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
An elephant’s trunk 🐘 is an amazing example of evolutionary development 🧬. It is a combined nose and upper lip that lengthened as the elephant’s ancestors became taller and their tusks grew bigger. With its heavy head, it needed an easy way to reach the ground.
@googlefactss#evolution
Автопортреты Joni Mitchell, которые стали обложками её релизов
• Clouds
• Ladies Of The Canyon
• Wild Things Run Fast
• Turbulent Indigo
• Taming The Tiger
• Both Sides Now
• Travelogue
• Dreamland
• The Reprise Albums (1968-1971)
Митчелл часто говорила, что она «художник, который выпускает песни».
Нельзя не заметить очевидную отсылку на другого художника, который за жизнь нарисовал с десяток автопортретов, — Винсента Ван Гога с отрезанным ухом на обложке «Turbulent Indigo».
#evolution
🌍 The island of New Caledonia is a biodiversity hotspot where ancient plants like the rare Amborella tree represent some of Earth’s oldest surviving flowering lineages, found nowhere else. ✨
#biodiversity⚡#islands⚡#evolution⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 The star-nosed mole detects prey in total darkness using its unique nose, covered in 22 finger-like tentacles packed with touch sensors. This extraordinary adaptation lets it identify and eat tiny insects and worms faster than any other mammal, even underwater. ✨
#animals⚡#adaptation⚡#evolution
👉subscribe Interesting Planet
🌎 The saiga antelope’s enlarged, drooping nose acts as a built-in air filter and cooler on the Central Asian steppes. When alarmed, herds can stampede at speeds up to 80 kilometers per hour. ✨
#animals⚡#evolution⚡#biodiversity
👉subscribe Interesting Planet
👉more Channels
🌎 The shoebill stork stands over 1.2 meters tall and has a massive, shoe-shaped bill up to 24 centimeters long. Native to East African swamps, this solitary bird hunts lungfish, frogs, and even baby crocodiles. ✨
#animals⚡#biodiversity⚡#evolution
👉subscribe Interesting Planet
👉more Channels
🌎 The platypus baffles scientists as it lays eggs like a reptile but produces milk and has fur like a mammal—a rare mix found in no other living animal. This odd, Australian creature even senses prey underwater using electroreceptors in its bill. ✨
#animals⚡#evolution⚡#Australia
👉subscribe Interesting Planet
🌎 Horseshoe crabs have remained virtually unchanged for about 450 million years. Despite their name, they are more closely related to spiders than to true crabs. Modern horseshoe crabs can be found along the Atlantic coast of North America and in Southeast Asia. ✨
#animals⚡#evolution⚡#fossils
👉subscribe Interesting Planet
👉more Channels
🌎 Living fossils like the chambered nautilus and horseshoe crab have changed little for hundreds of millions of years. The nautilus dates back over 500 million years, and its closest extinct relatives include ammonites, which died out with the dinosaurs. ✨
#evolution⚡#fossils⚡#animals
👉subscribe Interesting Planet
👉more Channels
🌎 Living fossils like the giant freshwater stingray and the Australian lungfish have remained almost unchanged for over 100 million years, surviving dramatic changes in Earth’s environment. The horseshoe crab’s body plan is so ancient, it first appeared 450 million years ago. ✨
#evolution⚡#fossils⚡#animals
👉subscribe Interesting Planet
👉more Channels
🌎 Some ancient animals have survived unchanged for millions of years. The coelacanth, once thought extinct, first appeared 400 million years ago and still swims deep ocean waters today. The horseshoe crab dates back over 450 million years, predating dinosaurs and even trees. ✨
#evolution⚡#fossils⚡#animals
👉subscribe Interesting Planet