Установить свойства виджета в 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
From #AS_Archive
Op-ed: Human Rights Under Siege: How security forces in #Oromia fuel terror and fear to control residents through lawlessness
Many have been shocked by reports of the wanton violence gripping #Ambo in West Shewa zone of Oromia, detailed in recent news coverage, including by Addis Standard, and a wave of social media posts over the past three days describing fear, abuse, and alleged attacks by a group known as “120.”
Yet these revelations are less surprising than they are confirming, pointing to a deeper breakdown of law and order in the region.
In January 2025, Addis Standard warned of the long-term risks posed by the expansion of irregular security structures and coercive enforcement practices across parts of Oromia.
Accounts now emerging from Ambo, of harassment, extortion, and unchecked violence, echo those earlier concerns about the human cost of a security approach increasingly described by residents as rule by fear.
Revisit the full version the 2025 op-ed in our archive for deeper context and analysis.
https://addisstandard.com/human-rights-under-siege-how-security-forces-in-oromia-fuel-terror-fear-to-control-residents-through-lawlessness/
#Ethiopia: Residents of #Ambo recount a city ‘under siege’ by ‘criminal gangs’ after social media revelations expose disturbing abuses
Residents of Ambo city, in west #Shewa zone of #Oromia regional state, say they are “living in fear” amid “a pattern of violence, intimidation, and impunity.”
Many are speaking up following a wave of social media posts over the past two days that have brought renewed scrutiny to rampant abuses in the city of civilians by organized group of men called “120”.
Multiple videos and pictures, shared widely on social media networks and echoed in messages sent to Addis Standard, describe incidents ranging from public beatings and arbitrary detention to extortion and, in some cases, killings.
While Addis Standard did not independently verify these videos and pictures, residents who reached out pleasing to share their accounts speak of a harrowing experience over the past “two years.”
“We are living in a city under siege,”
Read more: https://addisstandard.com/?p=56525
News: Fuel shortages deepen in #Addis_Abeba, regional cities as drivers endure prolonged queues
Drivers in Addis Abeba and several regional cities report worsening fuel shortages, with prolonged queues and dwindling supplies deepening the strain caused by recent price hikes.
At present, beyond rising costs, fuel is reportedly becoming increasingly scarce in cities including #Mekelle, #Jimma, #Ambo and #Bahir_Dar. Drivers who spoke to Addis Standard described spending hours in queues at fuel stations, often with no guarantee of securing supply.
A public transport driver in Mekelle said the situation has deteriorated sharply. “Beyond the price hike, it feels like fuel is heading toward complete disappearance. We are buying a 20-litre jerrycan for 8,000 birr, and that too after waiting in line for more than five hours,” he said.
Read more: https://addisstandard.com/?p=55586
News: EPRP calls for nationwide protest on May 8 amid concerns over electoral conditions
The Ethiopian People’s Revolutionary Party (#EPRP) has called for a nationwide peaceful protest to be held on May 8, 2026, citing what it described as the absence of “enabling conditions” for a credible election in #Ethiopia.
In a statement sent to Addis Standard today, the party said the planned demonstrations will take place in several major cities, including #Addis_Abeba, #Mekelle, #Bahir_Dar, #Gondar, #Hawassa, #Adama, and #Ambo, urging #Ethiopians to join what it described as a peaceful effort to demand political reforms.
The EPRP said it supports the transfer of power through elections but argued that current conditions do not allow for a “free, fair, and credible” vote. It accused the ruling Prosperity Party of attempting to conduct what it termed a “pseudo-election” aimed at extending its hold on power, describing the process as
Read more: https://addisstandard.com/?p=56410
Area Sales Manager
#ethiochicken_ethiopia
#business
#Bule | #Ambo | #Gambela | #Ginir | #Hosaena | #Yirgachefe | #Sheno
BSc Degree in Animal Science, Veterinary field of study
Duties & Responsibilities:
- Develop specific plans to ensure sales growth agent appointment in the territory
- Map how to achieve sales volume through prioritizing to make big achievement with minimum effort and shorter time
Quanitity Required: 20
Minimum Years Of Experience: #0_years
Deadline: December 16, 2023
How To Apply: Submit your applications (Cover Letter) including a detailed CV via email: [email protected]
N.B: Please title your application with the subject line: - " Area Sales Manager" and Specify the area you are applying for
#In_Depth_Analysis: The #Hormuz Entanglement: Why #Ethiopia’s fuel crisis is a perfect storm of #war, #graft, and #reform
While the immediate catalyst appears to be the high-stakes military escalation between the U.S., Israel, and Iran, a deeper look reveals that Ethiopia’s fuel misery is a complex entanglement. It is a “perfect storm” where geopolitical vulnerability, a domestic system rotting from within, and a painful macroeconomic experiment have collided to leave 120 million people running on empty.
Until the govt can clean its own house, root out the “senior decision-makers” profiting from the black market, and navigate the treacherous waters of Middle Eastern diplomacy, the accounts emerging from #Gonder to #Jimma to #Ambo, and from #Hawassa to #Bishoftu and #Mekelle, point to an Ethiopia that will remain running on empty.
It will be a country “stalled at the intersection of a distant war it cannot control and a local crisis of governance it has yet to master”...
https://addisstandard.com/?p=56099