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

Резултати

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

Пребарај: #communalresistanceseries

当前筛选 #communalresistanceseries清除筛选
Venezuelanalysis

@venanalysis · Post #1579 · 24.05.2024 г., 16:20

The Pancha Vásquez Commune in Apure State, Venezuela, focuses on cattle rearing and agriculture. Despite private land ownership limiting their capacity, they’ve established a Collection and Distribution Center to aid local producers. Discover how communards in the Venezuelan plains region [Llanos] produce, organize, and resist the impact of the US blockade. Click here to read the full interview 👉🏼shorturl.at/qfmo6 #communalresistanceseries

Venezuelanalysis

@venanalysis · Post #1589 · 31.05.2024 г., 20:54

Llaneros Resist the Blockade! Facing severe impacts from the US blockade, the Pancha Vásquez Commune has innovated with communal exchanges and local production shifts, such as using buffalo for dairy due to higher yield. The new Collection and Distribution Center aims to reduce intermediary dependency and stabilize food prices. Click here to read the full interview 👉🏼shorturl.at/T9XD6 #communalresistanceseries#sanctions

Venezuelanalysis

@venanalysis · Post #1632 · 05.07.2024 г., 19:56

The Coporo Indígena community in Apure, Venezuela, maintains its traditions and communal land practices despite violence and the US blockade. Recently, they welcomed 18 families displaced by violence, showing the strength of their communal ties. 'In Pumé society, we all work together and share the little that we have: shelter, water, and other goods, while the care of the community and the land is everybody’s task,' said Gladys García, spokesperson for the Coporo Indígena Communal Council. Read more in the full interview, part of the communal resistance series, here 👉🏼shorturl.at/uLjEo #communalresistanceseries#indigenouspeoples

Venezuelanalysis

@venanalysis · Post #1593 · 07.06.2024 г., 17:35

The Pancha Vásquez commune in Apure State, Venezuela, consisting of fourteen communal councils, embodies the region's deep-rooted traditions in agriculture and cattle rearing. It's also where Hugo Chávez sharpened his political vision from 1985-1988, intertwining his socialist ideals with the local folklore. From the legendary “El Silbón” to “La Sayona,” the tales Chávez encountered in Elorza have become a vital part of the area's folklore, reflecting the enduring impact of his legacy. Read the full interview here 👉🏼shorturl.at/jaxwE #communalresistanceseries#communes#HugoChavez

Venezuelanalysis

@venanalysis · Post #1786 · 25.10.2024 г., 19:00

Amazonian Huo̧ttö̧ja̧ People and the Bolivarian Process The Río Cataniapo Commune showcases the strength of Indigenous organizations in the Venezuelan Amazon, with approximately 1,500 participants committed to communal living and traditional agriculture. 'Our way of living is far more communitarian than the sabari way of life,' notes Irene Pérez, of the 5 de Julio-Las Pavas Communal Council, is an artisan and campesina, emphasizing their commitment to ensuring no one goes hungry. Read the full interview here: https://venezuelanalysis.com/general/amazonian-huo%cc%a7tto%cc%a7ja%cc%a7-people-and-the-bolivarian-process-rio-cataniapo-commune-part-ii/ #VAInterview#communalresistanceseries#communes#indigenouspeoples

Venezuelanalysis

@venanalysis · Post #1802 · 08.11.2024 г., 21:22

In the Río Cataniapo Commune, communal power and tradition intersect to sustain food sovereignty and resist the impacts of the US blockade. The commune produces its staple casabe from yuca, managing every step from harvest to market. Read the full interview here 👉🏼https://shorturl.at/WRgF9 #VAInterview#communalresistanceseries#communes#indigenouspeoples#communalandworkingclassresistance

Venezuelanalysis

@venanalysis · Post #1779 · 18.10.2024 г., 21:44

‘The Commune Is Nothing New Here’: The Rio Cataniapo Commune The Rio Cataniapo Commune, located in the Venezuelan Amazon, brings together 1,500 people, mainly Indigenous, to protect the Cataniapo River and develop a sustainable agricultural economy. As Enrique Martínez, a Huo̧ttö̧ja̧ leader, explains: ‘Self-government and collective ownership are part of our heritage.’ Indigenous leadership remains key, but the community also seeks modern improvements while preserving tradition. Read the full interview here 👉🏼https://shorturl.at/Xgst1 #VAInterview#communalresistanceseries#communes#indigenouspeoples#communalandworkingclassresistance

Venezuelanalysis

@venanalysis · Post #1649 · 12.07.2024 г., 14:25

In the Venezuelan plains region, a multi-generational group of women works to build Bolivarian socialism amid the US blockade. Nacidos para Vencer con Chávez [Born to Triumph with Chávez] is a women-led commune in a rural context with a long history of patriarchal oppression. This fledgling commune seized upon Chávez’s idea as a way forward in difficult times, attempting to build community and increase production, while connecting with other communes through the Communard Union. Read the full interview as part of the VA Communal Resistance Series 👉🏼shorturl.at/r06V5 #communalresistanceseries#communes#communalresistance#workingclassresistance