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

Резултати

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

Пребарај: #asmara

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

@addisstandardeng · Post #22009 · 13.04.2026 г., 08:01

News: #Eritrea’s President Isaias meets #China’s Horn of Africa envoy, calls for expanded role Eritrean President #Isaias_Afwerki met with Hu Changchun, China’s Special Envoy to the Horn of Africa, on 10 April 2026 at the Denden Guest House in #Asmara. According to Information Ministry of Eritrea, President Isaias reiterated Eritrea’s readiness to strengthen its engagement with China, emphasizing the need for a more prominent Chinese role in global & regional affairs amid what he described as heightened instability. He also highlighted Africa’s natural & human resources, underscoring what he called China’s expected contribution to their development. Ambassador Hu, for his part, expressed Beijing’s readiness to deepen its strategic partnership with Eritrea and to align development efforts in support of peace and stability in the Horn of Africa, the ministry said. Eritrea’s Foreign..... https://www.facebook.com/AddisstandardEng/posts/pfbid0a26QnfAYtXCvNLrMw4DJ9cPu2Qoa9fcMnhd8HospCtDC5JThQZJdxGCxoe1iWwWMl

Addis Standard

@addisstandardeng · Post #21496 · 23.02.2026 г., 08:32

News: #Saudi deputy foreign minister meets #Ethiopian FM week after Isaias talks in Asmara Saudi Arabia’s Vice Minister of Foreign Affairs, Waleed A. M. Elkhereiji, met with Ethiopia’s Minister of Foreign Affairs, Gedion Timothewos, in Addis Abeba, a week after holding talks with #Eritrean President #Isaias Afwerki in #Asmara. According to a statement from the Ethiopian Ministry of Foreign Affairs, the two officials discussed the “strong and longstanding bilateral relations” between Ethiopia and the Kingdom of Saudi Arabia, underscoring the importance of elevating ties to “a new high.” They also exchanged views on regional peace & security issues of mutual interest. Ethiopia’s Minister of Foreign Affairs offered no additional information in the statement. The meeting comes a week after Saudi Vice Foreign Minister Waleed A. M. Elkhereiji held talks in Asmara with Eritrean President... Read more: https://addisstandard.com/saudi-deputy-foreign-minister-meets-ethiopian-fm-week-after-isaias-talks-in-asmara/

Addis Standard

@addisstandardeng · Post #21370 · 11.02.2026 г., 12:55

News: #Amhara security bureau alleges #TPLF, #Eritrea involvement in ongoing conflicts The Amhara Regional State Peace and Security Bureau has alleged that ongoing conflicts in the Amhara region and elsewhere in #Ethiopia are receiving what it described as “leadership and logistical support from #Mekelle and #Asmara,” referring to the Tigray People’s Liberation Front (TPLF) and Eritrean government. In a statement released yesterday, the bureau said the public “must understand the reality” that the fighting is not only against groups it characterized as “extremists” but also involves what it described as internal and external actors. The statement further alleged that a group seeking control over the areas of #Wolkait, #Telemt, and #Raya had assigned what it called a mission to “internal extremist forces” and was mobilizing them to advance that objective. According to the bureau, the strategy aims to create conflicts across various zones and districts to... Read more: https://addisstandard.com/?p=55148