Установить свойства виджета в 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
#documentary#fascism
You voted - we did it! Here’s the first full documentary we uploaded on Telegram. Fascism: A History explores the nature of the ideology and how it’s been tainting societies long after Hitler. It’s also relevant to the current events unfolding in Ukraine.
The documentary reveals how NATO, created after WWII, carried on with colonial politics and expanded to the east under the auspices of bringing democracy.
Share your thoughts in the comments, and don’t forget to subscribe to our channel on Odysee.
All of our films are available on https://odysee.com/@RTDocumentary:4 and RTD.RT.com
Follow: https://t.me/rtdocumentary
Fascism at Work: Propaganda, Conspiracy, Lies, Hatred, and Incompetence in Ethiopia. Read more.
https://borkena.com/2026/03/23/ethiopia-fascism-at-work-propaganda-conspiracy-lies-hatred-and-incompetence-in-ethiopia/#Ethiopia#politics#EthiopianPolitics#Fascism
In the latest VA interview, Javier Couso, a keynote speaker at the recent World Congress Against Fascism in Caracas discussed the fascist attacks on Venezuela.
He highlighted Venezuela’s resistance to fascist tactics by liberal democracies, marking it as a key player in the global struggle for sovereignty and democracy. 'Venezuela is a beacon in the fight for sovereignty and true democracy,' stated Couso.
Read the full interview here 👉🏼https://shorturl.at/Ej6UL
#VAInterview#Fascism#PresidentialElections2024
Following President Nicolás Maduro’s inauguration for a third term on January 10, violent groups vandalized Venezuelan diplomatic offices in Lisbon (Portugal), Frankfurt (Germany), Medellín (Colombia), Vigo (Spain), and San José (Costa Rica). Venezuela’s Foreign Affairs Minister, Yván Gil, described these actions as “coordinated.”
“In a coordinated action by the extremists of deranged fascism, multiple consulates have been targeted by those who aim to damage our diplomatic missions like they do our beloved Bolivarian Homeland,” Gil stated on social media.
Read the full report: https://shorturl.at/tC2dt
#Venezuela#diplomaticmissions#fascism
Venezuela's National Assembly takes a dual stance against fascism and territorial disputes, passing anti-fascism legislation while reaffirming its claim over Essequibo amid alleged CIA and US Southern Command threats.
Read more 👉🏽https://shorturl.at/aeOP7
#fascism#laws#Essequibo#Venezuela
In the latest VA interview, Hindu Anderi discusses Venezuela’s Antifascist Law, which is nearing approval. She explains how the Platform for Solidarity with the Palestinian Cause is actively lobbying to include Zionism in the legislation. "Zionism is fascism’s twin... a racist movement based on supremacy and expansion," Anderi states.
Read the full interview here 👉🏼https://shorturl.at/xBM4T
#Fascism#InternationalSolidarity#Laws#Zionism
I play Stardew often as a cozy way to wind down and disconnect from the horrors. Today I see that the Trump Administration is using it for Slopaganda.
It's not even about anything consequential — apparently for the last 15 years whole milk was removed from school cafeterias, and it's been restored via executive order.
#USA#Politics#Slop#ImageGen#Fascism
The Stern Gang: Ideology, Politics and Terror, 1940–1949
by Joseph Heller
This study of Lehi (aka the Stern Gang) attempts to demythologize the image of this extremist, Zionist underground group. The book analyzes the party's split from the Irgun Zvai Leumi (National Military Organization) and its attempts to synthesize the politics and ideals of the right and left. Lehi's leader Stern stated that he incorporated elements of both the left and the right.
#Zionism#NationalBolshevism#Fascism#Nazism#Palestine
On Fascism and Other Maladies: A Conversation with Luis Britto García
One of Venezuela’s most respected intellectuals talks about fascism and corruption scandals in the lead-up to the presidential elections.
Read the full interview here 👉🏼shorturl.at/cexUZ
#VAInterview#LuisBrittoGarcia#Venezuela#presidentialelections2024#interview#corruption#fascism
Fascism Putin-style is not abstract rhetoric but a set of concrete signs: cult of personality, militarism, repression, imperial aggression. The article provides a clear analysis without euphemisms.
https://yep.uz/en/2025/09/putin-fascism-signs/
#fascism#putin#dictatorship#Uzbekistan repression #militarism#censorship#ukraine#zsymbols#russianworld