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

Резултати

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

Пребарај: #carbon

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

@amazingeo · Post #543 · 29.12.2025 г., 12:31

🌍 Tropical peat swamp forests store massive amounts of carbon in deep, soggy soils. Some areas in Southeast Asia hold peat deposits over 10 meters thick, locking away centuries of trapped carbon. ✨ #rainforest⚡#carbon⚡#wetlands⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #363 · 12.10.2025 г., 15:31

🌍 Some freshwater wetlands and deltas trap so much carbon in their soil that, hectare for hectare, they store more than most forests—making them powerful natural climate regulators. ✨ #wetlands⚡#delta⚡#carbon⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #286 · 23.09.2025 г., 12:31

🌍 The Arctic tundra’s permafrost acts like a giant freezer, locking away twice as much carbon as all the world’s forests combined, making it a crucial regulator for Earth’s climate. ✨ #permafrost⚡#tundra⚡#carbon⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #70 · 18.08.2025 г., 09:12

🌍 The global carbon cycle constantly moves carbon between the air, land, water, and living things. This cycle helps regulate Earth’s climate by storing and releasing carbon dioxide. ✨ #carbon⚡#climate⚡#cycles⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍

Amazing Geography 🌍

@amazingeo · Post #566 · 09.01.2026 г., 20:31

🌍 Canada holds more than 30% of the world’s forests, making it the top country for natural forest area. These forests store massive amounts of carbon and water—critical global natural resources. ✨ #resources⚡#forests⚡#carbon⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Корпус Вышивания!

@redstarsurplus · Post #5037 · 13.04.2026 г., 19:02

Grand Power кобура скрытого ношения на быстросъёмных крепежах с мягким слоем Alcantara внутри. Двойной подсумок Кобура скрытого ношения с Alcantara, с дополнительным магазином. ➡️#grandpower ➡️#моноблок ➡️#carbon НЕ ПРОДАЖА ОРУЖИЯ! ⚠️ Демонстрируется только для наглядности функционала. По вопросам заказа связывайтесь с нами📱 ПОДПИСЫВАЙТЕСЬ ЧТО БЫ НЕ ТЕРЯТЬСЯ: 📱MAX 📱VK @DP_KH

Amazing Geography 🌍

@amazingeo · Post #398 · 21.10.2025 г., 12:31

🌍 Some grassland soils are so fertile they can support crops for decades without added fertilizer. These deep, dark soils store huge amounts of carbon, helping stabilize the global climate. ✨ #grasslands⚡#soil⚡#carbon⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

#脚本#QuantumultX#Loon#Surge#Shadowrocket#Stash#Crack#Revenuecat#图像#摄影 ✅#Carbon-碳 👤 脚本作者: @chxm1023 📱 更新版本: 13.9 🕒 更新日期: 2024-03-18 📌 脚本功能: 解锁Pro 💳 特别说明: 一次性解锁,先开启规则,在进入软件即可!如果无效按[恢复购买]进行恢复! ⬇️ 下载地址: 点击下载 🔗 脚本链接: 长按复制 🔄 脚本转换: 点击传送 ✈️导航💬群组🤖投稿🎁福利

Amazing Geography 🌍

@amazingeo · Post #704 · 30.04.2026 г., 20:31

🌍 Argentina’s Pampas are vast temperate grasslands that grow some of the world’s richest soils. These grasslands support massive cattle herds and store huge amounts of carbon underground. ✨ #grasslands⚡#pampas⚡#carbon⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​