Установить свойства виджета в PySide можно не только через соответствующие методы и конструктор класса. Можно их изменять с помощью метода setProperty по имени.
btn = QPushButton("Click Me")
btn.setProperty("flat", True)
Это аналогично вызову
btn.setFlat(True)
Если указать несуществующее свойство, то оно просто создается
btn.setProperty("btnType", "super")
Получить его значение можно методом .property(name)
btn_type = btn.property("btnType")
Когда это может быть полезно?
▫️Можно просто хранить какие то данные в виджете и потом их доставать обратно
widget = QWidget()
widget.setProperty('my_data', 123)
print(widget.property('my_data'))
▫️ Назначая эти свойства разным виджетам можно потом отличить виджеты во время итераци по ним. Например, найти все кнопки со свойством my_data="superbtn".
Но ведь вместо кастомного свойства можно использовать objectName, будет тот же результат.
Да, но y ObjectName есть ограничение - только строки.
▫️ Если нам потребуется не просто поиск а, например, сортировка по числу, то свойства позволяют нам это сделать. Поддерживается любой тип данных
widget.setProperty('my_data', {'Key': 'value'})
widget.setProperty('order', 1)
all_widgets.sort(key=w: w.property('order'))
Но ведь Python позволяет всё вышеперечисленное сделать простым созданием атрибута у объекта
widget.order = 1
widget.my_data = 123
Да, но я думаю что не надо объяснять почему не стоит так делать. К тому же, если у виджета нет свойства то метод .property(name) вернет None, а отсутствующий атрибут выбросит исключение.
▫️ Действительно полезное применение кастомным свойствам - контроль стилей. Здесь атрибутами не обойтись, нужны именно свойства.
Дело в том, что в селекторах стилей можно указывать конкретные свойства виджетов на которые следует назначать стиль.
Просто запустите этот код
from PySide2.QtWidgets import *
if __name__ == "__main__":
app = QApplication([])
widget = QWidget(minimumWidth=300)
layout = QVBoxLayout(widget)
btn1 = QPushButton("Action 1")
btn2 = QPushButton("Action 2")
btn3 = QPushButton("Action 3", flat=True)
layout.addWidget(btn1)
layout.addWidget(btn2)
layout.addWidget(btn3)
# добавим кастомное свойство одной кнопке
btn1.setProperty("btnType", "super")
# добавляем стили
widget.setStyleSheet(
"""
QPushButton[btnType="super"] {
background-color: yellow;
color: red;
}
QPushButton[flat="true"] {
color: yellow;
}
"""
)
widget.show()
app.exec_()
С помощью селектора мы избирательно назначили стили на конкретные кнопки.
Как получить список всех кастомный свойств?
Функция получения списка кастомных свойств отличается от получения дефолтных.
def print_widget_dyn_properties(widget):
for prop_name in widget.dynamicPropertyNames():
property_name = prop_name.data().decode()
property_value = widget.property(property_name)
print(f"{property_name}: {property_value}")
#tricks#qt
@RusEmbMalta Press release
On the anniversary of the Declaration of Ukraine’s independence
🔷 On August 24, 2024, Kiev celebrated a state holiday – the #Independence Day of Ukraine.
The Kiev regime keeps trying to boast about its supposed “victories”, successful banderization and forced ukrainianization. It is the geopolitical and mercantile interests of the West that in fact stand behind its “support”
of Ukraine, while this country is assigned the role of a “puppet” and “cannon fodder”.
🔷 The representatives of Zelensky's junta hardly dare to publicly discuss the violation of the provisions adopted in July 1990.
🔷 The heirs of Goebbels do not mention the real losses of the country and the missed opportunities during 33 years of “independence”, total depopulation and loss of whole industries. Kiev got into complete dependence on financial and material submits of the West, for which future generations of Ukrainians will have to pay.
Read in full here
Since 1380, Iceland was ruled by Denmark. On December 1, 1918, Iceland became its own country with the same king as Denmark. In 1940, Iceland started making its own big decisions. On June 17, 1944, Iceland became a republic and stopped having a king.
👑🇮🇸
[Source]
@googlefactss#Iceland#History#Independence#FunFacts
🌍 Qadrli yurtdoshlar!
🇺🇿 O‘zbekiston Respublikasi Vazirlar Mahkamasi huzuridagi Biznes va tadbirkorlik oliy maktabi jamoasi barchangizni 18-noyabr – “O‘zbekiston Respublikasining Davlat bayrog‘i qabul qilingan kun” bilan muborakbod etadi!
🇺🇿 Mustaqilligimiz hamda tinchligimiz ramzi bayrog‘imiz, g‘urur va faxrimiz timsoli yuksaklarda abadiy hilpirab tursin!
#GraduateSchool#Uzbekistan#Flag#Independence
🔝Web-site |🔝Facebook | 🔝Instagram | 🔝Youtube
🇺🇿Biznes va tadbirkorlik oliy maktabi barcha yurtdoshlarimizni mustaqilligimizning 34 yilligi bilan muborakbod etadi.
🇺🇿Mustaqillik - yurtni, millatni birlashtiradigan yagona kuch, ko‘p millatli halqimizning irodasi, uning hurriyat haqidagi azaliy orzularidir.
🦅 Vatanimiz osmoni musaffo, sarhadlari daxlsiz, chegaralarimiz mustahkam, hayotimiz yana-da farovon, mustaqilligimiz va ravnaqimiz abadiy bo‘lsin!
#GraduateSchool#Independence#34years#Development
🔝Web-site |🔝Facebook |🔝Instagram | 🔝Youtube
🇺🇿Biznes va tadbirkorlik oliy maktabi barcha yurtdoshlarimizni mustaqilligimizning 33 yilligi bilan muborakbod etadi.
🇺🇿Mustaqillik - yurtni, millatni birlashtiradigan yagona kuch, ko‘p millatli halqimizning irodasi, uning hurriyat haqidagi azaliy orzularidir.
🇺🇿 Vatanimiz osmoni musaffo, sarhadlari daxlsiz, chegaralarimiz mustahkam, hayotimiz yana-da farovon, mustaqilligimiz va ravnaqimiz abadiy bo‘lsin!
🦅Barchamizga yana bir bor O‘zbekistonimiz Mustaqilligining 33 yilligi muborak bo‘lsin!
#GraduateSchool#Independence#33years#Development
🔝Web-site |🔝Facebook |🔝Instagram | 🔝Youtube
🇰🇪 Jamhuri Day (Swahili: “Republic Day”) — is Kenya’s national day, celebrated on December 12. It marks independence from Britain (12 Dec 1963) and becoming a republic (12 Dec 1964). Common observances: flag‑raising, presidential speeches, parades, cultural performances, and civic ceremonies. If you’re Kenyan or were there during the festivities, share your photos. @googlefactss#JamhuriDay#Kenya#Independence
Siku njema ya Jamhuri kwa Wakenya wote.
8 сентябр Президенти Ҷумҳурии Тоҷикистон, Пешвои миллат муҳтарам Эмомалӣ Раҳмон дар паёми шодбошии худ ба муносибати 33-солагии истиқлоли давлатии Тоҷикистон тамоми мардуми сарбаланди кишвар ва ҳамватанони бурунмарзиамонро самимона табрик гуфта, ба ҳамаи онҳо хонаи обод, саодати рӯзгор, сулҳу оромӣ, ки асоси хушбахтии халқамон ва ободиву сарсабзии Ватани маҳбубамон мебошад, инчунин, комёбиву барори кор орзу намуданд.
8 сентября Президент Республики Таджикистан, Лидер нации уважаемый Эмомали Рахмона в своем поздравительном послании по случаю 33-й годовщины независимости, поздравив народ Таджикистана и зарубежных соотечественников, пожелал всем им семейного благополучия, счастливой жизни, мира и спокойствия, которые являются основой благоустройства нашей любимой Родины, безмятежной жизни народа, а также новых достижений и успехов.
#ЭмомалиРахмон#EmomaliRahmon#Tajikistan#Президент#Таджики#Tajiks#Тоҷикон#Независимость#Independence
President.tj | Facebook | Instagram | Telegram | X | Youtube
Congratulations on the 34th anniversary of independence: Putin tops the list, but Mirziyoyev stresses multi-vector policy. Different priorities for domestic and foreign audiences: Central Asia in the president’s speech and Russia–China in the official greetings.
https://yep.uz/en/2025/09/uzbekistan-34th-independence-day-congratulations/
#uzbekistan#mirziyoyev#independence#putin#xijinping#trump#centralasia#politics#multivector
VCs Retreat from Crypto Market
In 2023, analysts noted a significant decline in venture capital investments in cryptocurrency projects, returning to levels reminiscent of 2017. However, some initiatives are aiming to revive the industry’s original spirit of independence from VC influence, at least in principle. Insights provided by Oleg CasCoin for ForkLog. Read more
#VC#Crypto#Investment#Market#Decline #2017 #ForkLog#OlegCasCoin#Independence#Initiatives#Analysis#Freedom#Trends#Industry#Finance#Blockchain#News#Updates#Economy#Future
🚀 AI TRENDS | OpenAI's Sam Altman Addresses AI Development Concerns and Recent Incident
OpenAI founder Sam Altman has expressed understanding of societal fears regarding the rapid development of artificial intelligence. According to Odaily, Altman acknowledged that the current period is marked by significant technological change, with associated risks escalating to systemic challenges at the societal level. He emphasized that AI power should not be concentrated in a few institutions and advocated for broader distribution through technological democratization and institutional constraints.
Addressing a recent incident where his residence was targeted with a Molotov cocktail, Altman admitted to underestimating the impact of public narratives and emotions amid AI-related anxieties. He also acknowledged mistakes in company governance and conflict management, offering apologies for past actions. Furthermore, Altman reiterated his decision to reject Elon Musk's attempts to control OpenAI, ensuring the company's independent development.
Previously, it was reported that the OpenAI founder's residence was attacked with a Molotov cocktail.
#AI#OpenAI#SamAltman#AIdevelopment#technologicalchange#AIsociety#democratization#institutionalconstraints#Molotovcocktail#publicnarratives#conflictmanagement#ElonMusk#companygovernance#independence