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

Резултати

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

Пребарај: #extinction

当前筛选 #extinction清除筛选
Amazing Geography 🌍

@amazingeo · Post #461 · 18.11.2025 г., 12:31

🌍 Since 1970, vertebrate wildlife populations have dropped by an average of nearly 70% worldwide. Habitat loss and pollution are major drivers of this rapid, ongoing global decline. ✨ #environment⚡#extinction⚡#biodiversity⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1381 · 22.04.2026 г., 12:11

🌎 Layers of ancient mud and sand, called sedimentary strata, hold natural records of Earth’s history. These layers show changes in climate, ocean levels, and even mass extinction events over millions of years. The famous K-T boundary, found in rock layers worldwide, marks the asteroid impact that ended the age of dinosaurs about 66 million years ago. ✨ #geology⚡#fossils⚡#extinction 👉subscribe Interesting Planet 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #267 · 19.09.2025 г., 20:12

🌍 Nearly 90% of the world’s wetlands have disappeared since 1700, shrinking vital habitats and reducing natural flood protection for millions of people living downstream. ✨ #wetlands⚡#extinction⚡#flooding⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Interesting Planet 🌍

@interesting_planet_facts · Post #779 · 19.09.2025 г., 03:22

🌎 The Steller’s sea cow, a giant marine mammal, was discovered in the Bering Sea in 1741 and went extinct just 27 years later due to overhunting. This species reached lengths up to 9 meters and fed on kelp, leaving no close living relatives today. ✨ #extinction⚡#megafauna⚡#ocean 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1229 · 16.01.2026 г., 22:11

🌎 Around 252 million years ago, the Permian-Triassic extinction wiped out about 90% of marine species and 70% of land vertebrates. Massive volcanic eruptions in Siberia released greenhouse gases that drove rapid global warming, ocean acidification, and low oxygen levels—making it the largest extinction event in Earth's history. ✨ #extinction⚡#volcanoes⚡#paleoclimate 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #438 · 27.07.2025 г., 16:22

🌎 The Gomphothere, an ancient cousin of elephants, once roamed the Americas with shovel-shaped lower jaws. These extinct giants sported four tusks instead of two, thriving for millions of years before vanishing at the end of the last Ice Age. ✨ #paleontology⚡#megafauna⚡#extinction 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #1346 · 19.03.2026 г., 12:11

🌎 Strange bones found on the island of Malta belong to dwarf elephants and hippos that once lived there. These animals evolved smaller sizes due to limited island resources. The dwarf elephant species Palaeoloxodon falconeri stood just one meter tall at the shoulder. ✨ #extinction⚡#paleontology⚡#Mediterranean 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1209 · 10.01.2026 г., 12:11

🌎 The moa, a group of flightless birds native to New Zealand, stood up to 3.6 meters tall and weighed over 200 kilograms. DNA analysis reveals that moas’ closest relatives are the small, flying South American tinamous, not ostriches or emus as once believed. ✨ #moa⚡#extinction⚡#paleontology 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #843 · 01.10.2025 г., 18:11

🌎 The giant moa, once native to New Zealand, stood up to 3.6 meters tall and weighed about 230 kilograms. Moa vanished around 600 years ago, likely due to hunting by early Polynesian settlers. DNA studies show there were at least nine distinct moa species before extinction. ✨ #moa⚡#extinction⚡#paleontology 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #743 · 13.09.2025 г., 20:22

🌎 The dodo bird, once native to Mauritius, vanished by the late 17th century. Little was documented about its appearance or habits, leaving scientists puzzled. Recent studies of preserved bones and rare historical notes suggest the dodo was likely grayish with small wings and weighed up to 18 kilograms. ✨ #dodo⚡#extinction⚡#mysteries 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1269 · 02.02.2026 г., 22:11

🌎 In Siberia, the woolly mammoth roamed the tundra until about 4,000 years ago. Some frozen mammoth carcasses still contain preserved hair, skin, and even stomach contents. Recent DNA studies show mammoths were closely related to modern Asian elephants. ✨ #mammoth⚡#extinction⚡#Siberia 👉subscribe Interesting Planet 👉more Channels ​

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