TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #381 · 23 окт.

Установить свойства виджета в 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

Hashtags

Резултати

Пронајдени 5 слични објави

Пребарај: #derg

当前筛选 #derg清除筛选
Addis Standard

@addisstandardeng · Post #22037 · 16.04.2026 г., 12:58

#Op_ed: Historical Divides, Emerging Alliances: Shifting politics, rising hopes for dialogue in #Ethiopia Ethiopia’s political crisis reflects not just a struggle for power but “fundamentally conflicting narratives about the country’s formation,” centered on Menelik II, writes Yaekob Yatene. One view sees expansion as “reunification,” while another defines it as “conquest.” These competing narratives have shaped modern politics and institutions. While the #Derg’s “Land to the Tiller” addressed inequality, and ethnic federalism enabled self-rule, both failed to resolve deeper demands for autonomy. Yaekob notes a shift: #Amhara actors now prioritize “the protection and survival of the Amhara,” even exploring “collaboration on the ground” with former rivals. He argues this “decoupling…from pseudo-unionist ideological control” could open space for “interest-based engagement.” https://addisstandard.com/?p=56531

Addis Standard

@addisstandardeng · Post #21469 · 20.02.2026 г., 10:44

#Op_ed: #TPLF at 51: Legacy of transformation, contention On 18 February 2026, the #Tigray People’s Liberation Front (TPLF) marked its 51st anniversary, which Ewnetu B. Debela calls “a milestone," highlighting its role as a "primary architect of the modern state" and “a deeply polarizing force.” Since its 1975 insurgency origins, the TPLF has evolved from a guerrilla movement into a governing elite, overthrowing the #Derg regime and overseeing decades of "sustained economic growth" and infrastructural expansion. Critics note a "concentration of power" that stifled opposition, where "dissent was frequently framed as a matter of national security." “The history of the TPLF resists simple verdicts,” Ewnetu concludes, urging #Ethiopia to pursue “a sober reckoning” with this complex legacy. https://addisstandard.com/?p=55264

Addis Standard

@addisstandardeng · Post #21694 · 12.03.2026 г., 14:55

Mulugeta Bekele: the jailed and tortured scientist who kept #Ethiopian#physics alive Mulugeta Bekele paid a heavy price for remaining in #Ethiopia in the 1970s and 1980s. While many other academics had fled their homeland to avoid being targeted by its military rulers, Mulugeta did not. He stayed to teach #physics, almost single-handedly keeping it alive in the country. But Mulugeta was arrested and brutally tortured by members of the #Derg, Ethiopia’s ruling military junta. “I still have scars,” he says when we meet at his tiny, second-floor office at Addis Ababa University (AAU) in January 2026. Gentle and softly spoken, Mulugeta, 79, is formally retired but still active as a research physicist. In 2012 his efforts led to him being awarded the Sakharov prize by the American Physical Society (APS) “for his tireless efforts in defence of human rights and freedom of expression and education.... https://physicsworld.com/a/mulugeta-bekele-the-jailed-and-tortured-scientist-who-kept-ethiopian-physics-alive/

Addis Standard

@addisstandardeng · Post #21131 · 20.01.2026 г., 09:54

#Book_Review: A Ten Minute Mission: The Least Price for Freedom by W. Hundee Hurrisoo In this book review, Ababiyaa Ahmed Ajmel examines W. Hundee Hurrisoo’s A Ten Minute Mission: The Least Price for Freedom, calling it more than a prison memoir—it exposes the “moral and political logic” behind the #Derg regime’s terror. As editor of Bariisaa, #Ethiopia’s first #Oromo-language newspaper, Hundee saw his symbol of “freedom’s light” targeted for erasure. Arrested under the false pretense of a “ten-minute mission,” he endured “4,040 days” in prisons like the Grand Palace and Maikalawi, where torture tools such as the “Stalin stick” broke bodies. The reviewer emphasizes that “the memoir is not only a record of erasure” but also affirms the Oromo concept of Jirra: “we are here, we exist”—a truth echoed by today’s #Qeerroo generation. https://addisstandard.com/?p=54635

Addis Standard

@addisstandardeng · Post #21511 · 24.02.2026 г., 10:33

#Commentary: From #Derg to #EPRDF to Present: #Ethiopia’s unfinished nation-state-building journey In this commentary, Merera Gudina traces Ethiopia’s persistent instability to failed state-building across the imperial, Derg, and EPRDF eras. He argues each collapse stemmed from rulers prioritizing personal power over the "equality of Ethiopian peoples" and their "thirst for development." Merera recounts how Emperor Haile Selassie’s 60-year reign ended ignominiously, even as hundreds of thousands perished in #Wollo, while the Derg, despite abolishing feudal landholding, succumbed to an "extreme lust for power," enforcing Stalinist "#Red_Terror" and destroying movements. The EPRDF era, meant to resolve the "nationalities question," became a 27-year "crude joke." Today, Ethiopia faces a "final frontier," requiring an end to "political theater" and "sham elections" for genuine unity. https://addisstandard.com/?p=55338