Установить свойства виджета в 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
News: #CBE says digital platforms handled over nine trillion birr, accounting for 87% of half-year transactions
The Commercial Bank of Ethiopia (CBE) says transactions conducted through its digital banking platforms surpassed nine trillion birr in the first half of the 2025/26 fiscal year, accounting for nearly 88 percent of the bank’s total transfers and payments.
The figures were disclosed during CBE’s half-year performance review conference, where Wegayehu Gebremariam, Vice President for Strategic Planning and Transformation, presented the bank’s six-month performance report.
According to Wegayehu, digital channels facilitated more than nine trillion birr in transactions during the reporting period, representing 87.9 percent of total banking transactions.
He said CBE accounted for 73 percent of the country’s total digital transactions and payments in the previous fiscal year, adding that current trends indicate the bank is likely to maintain its....
Read more: https://addisstandard.com/?p=54768
News: #CBE launches digital wallet for inward foreign currency transfers
The Commercial Bank of #Ethiopia (CBE), in partnership with local company StarPay Financial Services, has launched a digital wallet application, “CBE Connect,” to facilitate the transfer of foreign currency into the country.
Ephrem Mekuria, Executive Vice President for Corporate Services at the Commercial Bank of Ethiopia, attended the launch ceremony yesterday, alongside ambassadors and senior bank officials.
Ephrem encouraged customers to use legal channels instead of informal foreign exchange markets during his speech at the event. He added that CBE Connect allows users to send money easily using international payment cards such as Visa and Mastercard, as well as through licensed foreign remittance agents.
The bank noted that the digital wallet aims to support international customers, boost foreign currency inflows, and provide the Ethiopian diaspora with a simple, cost-free platform to send and receive remittances.
Ethiopia’s Commercial Bank Announces Digital Banking Disruptions. Read more.
https://borkena.com/2026/05/03/ethiopias-commercial-bank-announces-digital-banking-disruptions/#Ethiopia#bank#CBE#EthiopianNews
#Policy_Brief: Consolidate or Collapse: Mergers and acquisitions as strategic lifeline for #Ethiopian banks
In this policy brief, Samson Hailu contends that Ethiopia’s banking sector is entering a critical phase, as consolidation —particularly through mergers and acquisitions— shifts from a private-sector discussion to a policy priority of the #NBE under Governor Eyob Tekalign.
Although the sector has expanded to 31 banks, the #CBE continues to dominate, leaving smaller institutions vulnerable. Stress tests highlight significant capital and liquidity risks, reinforcing the author’s warning that “consolidation is not merely a strategic choice but a requirement for survival.”
He recommends that smaller “third-generation” banks form partnerships with larger private banks and endorses a “guided voluntary” approach, designed not to mandate consolidation but to facilitate market-led combination.
https://addisstandard.com/?p=56167