Когда разрабатываете свой 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
Farewell to Ambassador Mzuvukile Maqetuka
📅 March 31 marks the final day of the tenure of South African Ambassador to Russia and Belarus Mzuvukile Maqetuka. Today, he is departing from Russia.
💌 An excerpt from a farewell letter by the Honorary Consul of South Africa in Yekaterinburg, Sergey Mazurkevich, to Ambassador Maqetuka:
"All our meetings have been truly memorable, and each time, you have emphasized the importance of fostering strong people-to-people ties. Your words have been a source of inspiration, guiding my efforts in this role. (...)
Your Excellency, it has been an honor, privilege, and pleasure to know you personally and to serve as the Honorary Consul of South Africa under your leadership. My team and I remain committed to strengthening the ties between our nations, guided by the priorities you have set. Please accept our heartfelt gratitude, and our best wishes for your future endeavors."
🌍 Ambassador Maqetuka's dedication to building lasting connections and promoting cooperation between Russia and South Africa will be remembered and appreciated. Wishing him success in his future endeavors!
#SouthAfrica#Russia#Diplomacy#Ambassador#InternationalRelations#Maqetuka#Mazurkevich
📚 At the international book festival Red Line, the Russian edition of Jim is Tired of Jo’burg by former South African Ambassador to Russia Mzuvukile Maqetuka was officially presented.
💬 In a lively dialogue, translator Dr. Dmitry Pobedash and editor Dr. Mikhail Brodsky explored the challenges of literary translation and shared fascinating stories about 🇿🇦 South Africa with the audience.
🤝 The event was made possible with the support of Ural Federal University Press and the Office of the Honorary Consul of South Africa in Yekaterinburg.
#Culture#Literature#Festivals#SouthAfrica#Yekaterinburg#Translation#Maqetuka#Mazurkevich#UrFU
South Africa from A to Z: students, graduates, and professors of the Institute of International Relations (IIR) discovered many fascinating facts about the country!
On March 22, South African English teacher Samora "Sam" Poswa held an engaging presentation at IIR, sharing insights about his homeland and answering numerous questions. The event was organized with the support of the Office of the Honorary Consul of South Africa in Yekaterinburg.
The Office staff presented IIR Rector Dr. Irina Vylegzhanina with the Russian edition of Jim Is Tired of Jo’burg by South African Ambassador to Russia Mzuvukile Maqetuka, translated in 2024. They also spoke about the history of the project initiated by HC of South Africa Sergey Mazurkevich.
#SouthAfrica#internationalrelations#education#culture#IIR#IMS#Maqetuka#Mazurkevich#Yekaterinburg
Во вторник 10 декабря Почётный консул Сергей Мазуркевич встретился в Москве с Послом ЮАР Мзувукиле Макетукой.
Они обсудили текущие проекты офиса Почётного консула ЮАР и планы на 2025 год.
#встречи#новости#Посол#Макетука#Мазуркевич
_________________
On Tuesday, December 10, Honorary Consul Sergey Mazurkevich met with South African Ambassador Mzuvukile Maqetuka in Moscow.
They discussed current projects of the Honorary Consul's office and plans for 2025.
#meetings#news#Ambassador#Maqetuka#Mazurkevich
🇿🇦📖Jim may be tired of Jo’burg, but Yekaterinburg certainly isn’t tired of Jim!
📚 On August 22–24, the Red Line Book Festival (“Krasnaya Strokа”) — Yekaterinburg’s international book festival — will feature a new presentation of the Russian translation of Mzuvukile Maqetuka’s novel Jim Is Tired of Jo’burg.
📍The presentation format was discussed by representatives of the Office of the Honorary Consul of South Africa, translator Dr. Dmitry Pobedash (📸 right), and Dr. Aleksey Podchinyonov, the CEO of the Ural University Press (📸 left).
🗓 A year ago, an earlier presentation of translated chapters took place at the same festival:
🔗https://t.me/sarconsulurals/1340
📌 Details about the exact time and venue will be announced soon.
#SouthAfrica#Yekaterinburg#Ural#RedLineFestival#Literature#AfricanLiterature#Translation#Maqetuka#UrFU#JimIsTiredOfJoburg