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

Резултати

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

Пребарај: #nessie

当前筛选 #nessie清除筛选
TONlines – News

@tonlines · Post #6826 · 18.04.2025 г., 07:32

⚡️Gatto | Official Channel: Quahilles Battle Guidelines and Deadlines #GTON#Nessie The Gatto | Official Channel provides an update on the legendary battle against Nessie. Followers are invited to participate by forming a squad of heroes and adhering to strategic guidelines, including offerings of $GTON, to thwart the monster. Action is required by April 19, 07:00 UTC. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #6788 · 16.04.2025 г., 07:38

Gatto | Official Channel (18+): Quahilles Update and Strategy #GTON#Nessie Gatto | Official Channel (18+) reports on the latest battle developments in Quahilles. The energy beam malfunction set back the fight against Nessie, but new strategies involving heroes Dogo, Sultraccoon, and Chimpunk are in place. Follow placement instructions carefully to maximize damage and stop the monster. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #6739 · 13.04.2025 г., 07:31

⚡️Gatto: Prepare Your Heroes for Battle with Nessie #GTON#Nessie The Gatto Official Channel instructs players on how to position their heroes, Homiekins, Bullffalo, and Mushmallow, in the battle against the Loch Ness monster. Important rules include having a complete squad and burning $GTON for offerings. Players must act by April 14 to prevent the monster from advancing. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #6875 · 21.04.2025 г., 11:30

Gatto | Official Channel: A New Chapter with Nessie #Nessie#GattoVerse The GattoVerse was once again visited by Nessie, revealed not to be a monster but a protective mother of her species. After hatching her offspring, Nessie passed the responsibility of their care to the event participants who achieved 1000 damage points, rewarding them through the league. Source: link @tonlines

TONlines – News

@tonlines · Post #6804 · 17.04.2025 г., 07:32

⚡️Gatto: Join the Battle Against Nessie #GTON#Nessie#Gatto The Gatto channel presents Quahilles’ latest effort to defeat the monster Nessie, urging followers to support with their squad. Instructions and event details are available, with a deadline on April 18. Participants can enhance their impact by strategically positioning their heroes and making offerings. Source: link @tonlines

TONlines – News

@tonlines · Post #6718 · 11.04.2025 г., 14:16

Weekend Tournament and PvP Events on Gatto Channel #Gatto#Nessie#GTON The Gatto | Official Channel announces a double event featuring a Weekend tournament and a PvP team challenge. Participants can earn various rewards by battling for $GTON, with events launching on April 11th. Highlights include a leaderboard-driven tournament and exclusive rewards for PvP victories. Source: link @tonlines

TONlines – News

@tonlines · Post #6730 · 12.04.2025 г., 07:36

⚡️Gatto: Quahilles III Battle Instructions #GTON#Quahilles#Nessie The Gatto channel instructs players on how to prepare their squads to fight the approaching Loch Ness monster. Players must assemble and position their heroes, Pepperaptor, Hedgehog, and Dragoad, on the field by April 13, following strict placement rules. Burning $GTON is required to enhance squad damage through offerings. Source: link @tonlines