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

Резултати

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

Пребарај: #animals

当前筛选 #animals清除筛选
Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40547 · 16.01.2026 г., 23:01

The scientific name for "coyote" is canis latrans, which literally means "barking dog", a fitting description for its wide variety of yips, howls, and barks used for communication, with the name coming from the Aztec word for the animal. @googlefactss#animals

Hashtags

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40082 · 13.11.2025 г., 20:50

Female elephants stay with the same herd their entire lives. Males only remain with the herd until they are 12 to 15 years old. The Male elephants then either join a "bachelor" herd or they live alone only rejoining the females during mating season. @googlefactss#animals

Hashtags

EKOLOG.UZ| ENG

@ekologuzenglish · Post #11860 · 09.03.2026 г., 15:02

#Animals Animals help each other too, and sometimes they do it more sincerely than humans. In nature, there are many amazing examples of cooperation: birds warn their flock about danger, dolphins support injured companions, elephants protect their calves, and some animals share food with those who are weak. This invisible bond of support and care is part of the harmony of nature. In the wild, survival often depends on cooperation and strong social connections. By observing animals, we learn a simple truth: the world is sustained not only by strength, but also by compassion, trust, and mutual help. 🐾🌿☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot Instagram | Facebook | Twitter | Sayt | Youtube.

Hashtags

Daily Channels

@dailychannels · Post #6553 · 19.12.2025 г., 01:00

Channel: Dangerous Earth Members: ~5.44K 💢 Username: @dangerousground Description: Craters, volcanoes, avalanches, brutal animal scenes, deadly attacks by predators and many other strange displays of the forces of nature and its inhabitants. Buy ads: https://telega.io/c/dangerousground 🏷 Tags: #animals https://telegramchannels.me/channels/dangerousground

Hashtags

123•••5•••10•••15•••20•••25•••30•••35•••40•••45•••50•••55•••60•••6566
ПретходнаСтраница 1 од 66Следна