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

Резултати

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

Пребарај: #uel

当前筛选 #uel清除筛选
Football Daily News

@FootyNews · Post #112806 · 18.05.2023 г., 22:09

Sevilla have won 100% of the #UEL semi-finals they've contested: ◉ 2005/06 v Schalke ◉ 2006/07 v Osasuna ◉ 2013/14 v Valencia ◉ 2014/15 v Fiorentina ◉ 2015/16 v Shaktar ◉ 2019/20 v Man Utd ◉ 2022/23 v Juventus And they've gone on to lift the trophy every single time. 🤯https://t.co/QoHm1XFxnh

Hashtags

Football Daily News

@FootyNews · Post #112798 · 18.05.2023 г., 19:09

RT @Squawka_Live: 19-year-old England U20 international Samuel Iling-Junior starts for Juventus for only the third time. Thrown in at the deep end. 🤿 #UELhttps://t.co/m5XW1Rx6Cihttps://t.co/bBFN7rfQGO

Hashtags

Football Daily News

@FootyNews · Post #112594 · 11.05.2023 г., 20:09

RT @Squawka_Live: Lucas Ocampos first-half by numbers vs Juventus: 100% passing accuracy 100% dribbles completed 6 touches in opp. box (most) 5 shots (most) 5 duels won (Sevilla most) 2 chances created (joint-most) 1 assist 0.73 xG Posting FT stats at HT. 🥶 #UELhttps://t.co/0SXs7yyirm

Hashtags

Football Daily News

@FootyNews · Post #112593 · 11.05.2023 г., 19:10

RT @Squawka_Live: Juventus' record at home in the Europa League since 2009: 🤝 0-0 ✅ 3-1 ✅ 1-0 ✅ 1-0 🤝 3-3 🤝 1-1 🤝 0-0 ✅ 2-0 🤝 1-1 ✅ 2-1 🤝 0-0 🤝 1-1 ✅ 1-0 ✅ 1-0 Mission impossible for Sevilla? #UELhttps://t.co/ulnbRPSOGg

Hashtags

Football Daily News

@FootyNews · Post #111952 · 20.04.2023 г., 22:09

RT @Squawka_Live: Paulo Dybala's game by numbers vs Feyenoord: 47 minutes played 38 touches 6 shots 3 duels won 3 chances created 3 shots on target 1 goal 0.31xG Impact. 💥#UELhttps://t.co/awnOgtSlY4

Hashtags

Football Daily News

@FootyNews · Post #111949 · 20.04.2023 г., 22:09

RT @Squawka_Live: No Premier League player has made more errors leading to a goal across all competitions than David De Gea since the start of last season (5). 😬#UELhttps://t.co/4g3ld0CKW4

Hashtags

Football Daily News

@FootyNews · Post #111945 · 20.04.2023 г., 21:10

RT @Squawka_Live: Man Utd in the first leg vs Sevilla: ◉ Score two own goals Man Utd in the second leg vs. Sevilla: ◉ Commit two errors leading to goals Shooting themselves in the foot. 🔫#UELhttps://t.co/Bv4VnTGCbl

Hashtags

Football Daily News

@FootyNews · Post #111943 · 20.04.2023 г., 20:09

RT @Squawka_Live: Erik Lamela created more chances than any other player in the first half vs. Man Utd (3). He also provided the assist for Youssef En-Nesyri, his first for Sevilla this season. 🅰️#UELhttps://t.co/baxztemlkr

Hashtags

Football Daily News

@FootyNews · Post #111941 · 20.04.2023 г., 18:09

RT @Squawka_Live: Sevilla XI: Bono; Navas, Bade, Marcao, Acuna; Gudelj, Fernando; Ocampos, Rakitic, Lamela; En-Nesyri. Man Utd XI: De Gea; Wan-Bissaka, Maguire, Lindelof, Dalot; Eriksen, Casemiro, Sabitzer; Antony, Martial, Sancho. #UEL

Hashtags

12
ПретходнаСтраница 1 од 2Следна