Установить свойства виджета в 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
The EPRP Rises Again: A Fearless Spirit Confronts Abiy’s Fearful Regime. Read more.
https://borkena.com/2025/12/07/ethiopia-eprp-rises-again-a-fearless-spirit-confronts-abiys-fearful-regime/#Ethiopia#politics#EPRP
EPRP Central Committee Meeting, Vows To Intensify Its Struggle For Ethiopians. Read more.
https://borkena.com/2025/11/19/eprp-central-committee-meeting-vows-to-intensify-its-struggle-for-ethiopians/#Ethiopia#Politics#EPRP
EPRP Calls For A Public Meeting In Addis Ababa. Read more.
https://borkena.com/2025/11/22/ethiopia-eprp-calls-for-a-public-meeting-in-addis-ababa/#Ethiopia#News#EPRP#PublicMeeting
News: #EPRP says politician #Yeshiwas Assefa arrested, calls for immediate release
The #Ethiopian People’s Revolutionary Party (EPRP) has announced that politician Yeshiwas Assefa has been arrested, saying it confirmed the development through his family members.
In a statement issued today, the party said Yeshiwas was taken into custody yesterday, describing the arrest as part of what it called the government’s continued crackdown on citizens engaged in peaceful political activity.
“This is one of the countless acts that demonstrate the government’s ongoing suppression of citizens engaging in peaceful political activities,” the statement read.
The EPRP further argued that such actions cast doubt on the credibility of the upcoming elections, which ruling party officials have repeatedly pledged will be free, fair and democratic. Instead, the party said, the current
https://web.facebook.com/AddisstandardEng/posts/pfbid0haYBwZFd8QeABk6i1v9kN4LtHyVXkPGG4mFcjx4T6UPUAx1SVkJ5PCi2FpXQ74Col
EPRP Press Conference on planned demonstration. Watch it.
https://borkena.com/2026/04/15/eprp-press-conference-on-planned-demonstration/#Ethiopia#News#EPRP#EthiopianNews#politics#EthiopianPolitics
EPRP Holding Its Public Meeting This Saturday In Addis Ababa. Read. https://borkena.com/2025/12/03/eprp-holding-its-public-meeting-this-saturday-in-addis-ababa/#Ethiopia#EPRP#AddisAbaba#opposition
News: #EPRP signals readiness to bypass electoral board for nationwide protests
Ethiopian People’s Revolutionary Party says it will proceed with planned demonstrations in ten cities on 8 May, 2026, even if it does not receive approval from the National Election Board of Ethiopia, citing constitutional guarantees on the right to assembly.
Speaking to Addis Standard, #Mistireslassie_Tamrat, EPRP’s General Secretary, said the party had formally notified #NEBE ahead of the planned protests but has yet to receive any response.
“Regarding the letter we submitted to the Electoral Board, we have not received any response so far; they haven’t notified us of anything, and we are still waiting,” she said.
Despite the lack of communication, Mistireslassie indicated that the party is prepared to move forward outside the electoral framework if necessary. “If this demonstration cannot proceed through the Electoral Board's framework, we will
Read more: https://addisstandard.com/?p=56537