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

Резултати

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

Пребарај: #insects

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

@googlefactss · Post #40801 · 15.03.2026 г., 15:03

The praying mantis is the only insect that can turn its head rotating it up to 180 degrees due to a flexible joint between the head and prothorax. This unique, adaptation allows them to track prey and monitor surroundings without moving their bodies. @googlefactss#insects

Hashtags

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #39916 · 10.10.2025 г., 10:50

A tarantula hawk wasp finds and stings a tarantula then carries the paralyzed spider to its lair, where it lays a single egg on the spider before burying it alive. Once the egg hatches, the larva eats the inside of the still-living spider, being careful to avoid vital organs until last. @googlefactss#insects

Hashtags

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40524 · 11.01.2026 г., 15:05

Dragonfly nymphs (larvae) breathe and move using their anus, drawing water in for gas exchange (breathing via internal rectal gills) and expelling it forcefully for jet propulsion to escape danger or catch prey, a remarkable adaptation for their aquatic life. @googlefactss#insects#nowyouknow

Interesting Planet 🌍

@interesting_planet_facts · Post #421 · 26.07.2025 г., 00:22

🌎 Some cicada species spend 17 years underground as nymphs before emerging in huge synchronized swarms. This odd lifecycle helps them overwhelm predators and ensures their survival. ✨ #insects⚡#evolution⚡#adaptation 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #1159 · 24.12.2025 г., 12:11

🌎 The orchid mantis of Southeast Asia blends in with flowers thanks to petal-shaped limbs and white, pink, or yellow coloring that matches local orchids. This insect both camouflages from predators and attracts pollinators, which it ambushes for food. ✨ #animals⚡#camouflage⚡#insects 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1246 · 22.01.2026 г., 18:11

🌎 The Indian leaf butterfly disguises itself as a dead leaf when at rest, with veins and brown patterns mimicking real foliage. When disturbed, it reveals bright blue and orange wings underneath—stunning colors that help startle predators. This butterfly is native to forests in South and Southeast Asia. ✨ #camouflage⚡#adaptation⚡#insects 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #378 · 21.07.2025 г., 18:22

🌎 The mimicry leaf insect looks exactly like a real leaf, down to brown spots that resemble decay. This remarkable disguise protects it from hungry predators by blending perfectly into the forest floor. ✨ #insects⚡#camouflage⚡#adaptation 👉subscribe Interesting Planet

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