Когда разрабатываете свой 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
The country with least females is Qatar, having about 266 men for every 100 women, this is one of the world’s largest gender gaps, caused in part by male migrant labor from India, Nepal, Bangladesh and the Philippines.
@googlefactss
#Demographics#FunFact
🌍 In 1800, fewer than 1 billion people lived on Earth. Today, the world population has soared past 8 billion, with more than half living in urban areas like cities and large towns. ✨
#population⚡#urbanization⚡#demographics⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 By 2050, city dwellers are expected to make up nearly 70% of the global population. Urban areas are now growing twice as fast as rural regions, reshaping how billions of people live. ✨
#urbanization⚡#cities⚡#demographics⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 More than 1 in 3 people alive today live in just two countries—China and India. Together, their populations make up over 2.7 billion people, shaping trends in language, culture, and the global economy. ✨
#population⚡#demographics⚡#Asia⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In November 2022, the world’s population reached 8 billion for the first time, doubling in just 48 years since 1974—a record pace in human history for global population growth. ✨
#population⚡#demographics⚡#growth⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In 2023, India gained over 13 million people—more than the total population of some countries. This rapid growth boosts its status as the planet’s most populous nation. ✨
#population⚡#demographics⚡#growth⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In 2023, Ethiopia recorded the world’s highest annual natural population increase, adding nearly 2.7 million people in a single year—more than many countries’ entire populations. ✨
#population⚡#demographics⚡#growth⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
Ukraine Considers Raising Retirement Age to 67
Facing a demographic crisis and labor shortages, Ukraine is considering raising the retirement age to 67. Currently, about 10.5 million pensioners equal the number of working-age citizens, straining the pension system. Experts warn the situation will worsen by 2040 due to an aging population. This discussion comes amid record population decline and restrictions on young Ukrainians leaving the country.
#Ukraine#pension#demographics#crisis
The main news of Russia and the world ishere.
🌍 Over one million people are added to the world population roughly every five days. The fastest-growing regions are now in parts of Africa, where birth rates remain among the highest globally. ✨
#demographics⚡#growth⚡#continents⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In 2022, the number of international migrants reached an estimated 281 million—more than triple the figure from 1970—making up 3.6% of the world’s total population today. ✨
#migration⚡#demographics⚡#movement⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 India is now the world’s most populous country, with more people than any other nation. Its population surpassed 1.4 billion in 2023, highlighting rapid growth and demographic change. ✨
#India⚡#population⚡#demographics⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍