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

Резултати

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

Пребарај: #polar

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

@amazingeo · Post #78 · 19.08.2025 г., 16:12

🌍 The polar climate zones, found near the North and South Poles, have average summer temperatures below 10°C. Here, permanent ice and tundra dominate, with only hardy mosses and lichens surviving. ✨ #climate⚡#polar⚡#tundra⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍

Universe Mysteries 🪐

@cosmomyst · Post #298 · 19.09.2025 г., 20:11

🪐 The galaxy NGC 2685, also called the Helix Galaxy, is a striking example of a "polar ring galaxy," where a large ring of stars and gas orbits nearly perpendicular to the main disk. This rare and twisted structure probably formed when NGC 2685 captured material from another galaxy, creating a cosmic spectacle that challenges our ideas of how galaxies grow and evolve. ✨ #galaxies⚡#shapes⚡#polar⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Amazing Geography 🌍

@amazingeo · Post #699 · 23.04.2026 г., 20:31

🌍 Antarctica is home to “blue ice” areas where strong winds strip away snow and expose centuries-old glacier ice, creating shimmering fields that reflect nearly as much sunlight as fresh snow. ✨ #glaciers⚡#Antarctica⚡#polar⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #658 · 11.03.2026 г., 20:31

🌍 In Antarctica’s Dry Valleys, glaciers flow slowly over bare rock and create icy waterfalls called “ice falls,” frozen in mid-cascade for years in the planet’s coldest, driest desert region. ✨ #glaciers⚡#Antarctica⚡#polar⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #237 · 14.09.2025 г., 20:12

🌍 In Antarctica’s McMurdo Dry Valleys, some glaciers create striking red waterfalls called “Blood Falls.” The color comes from iron-rich water oxidizing as it flows out of the ice. ✨ #glaciers⚡#polar⚡#Antarctica⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #163 · 02.09.2025 г., 16:12

🌍 Some Antarctic glaciers can move several meters in a single day, driven by gravity and melting underneath. These "ice rivers" shape the landscape faster than most people imagine. ✨ #glaciers⚡#polar⚡#Antarctica⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #317 · 30.09.2025 г., 20:31

🌍 In polar regions, "diamond dust" can fall from clear skies. This glittering ice fog is made of tiny ice crystals that drift in the air, sparkling in sunlight even when there’s no snowstorm. ✨ #glaciers⚡#polar⚡#arctic⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #537 · 26.12.2025 г., 12:31

🌍 In polar regions, some glaciers move so fast they form towering "ice cliffs" over 100 meters high at their edges. These dramatic walls can collapse suddenly into the sea during major calving events. ✨ #glaciers⚡#polar⚡#ice⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #197 · 08.09.2025 г., 03:12

🌍 Some polar glaciers are so thick that their bottoms lie below sea level for hundreds of meters. These vast "marine ice sheets" hold enough frozen water to alter global coastlines if they melt. ✨ #glaciers⚡#polar⚡#ice⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #98 · 22.08.2025 г., 20:12

🌍 Some glaciers can glow blue beneath the surface. This vivid color appears when dense, compressed ice absorbs red light and scatters only the blue, creating striking icy caverns in polar regions. ✨ #glaciers⚡#polar⚡#ice⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #578 · 15.01.2026 г., 20:31

🌍 Some polar lakes never see sunlight and stay covered with ice year-round. Microbes living under this ice survive in complete darkness, making them some of the most isolated life forms on Earth. ✨ #glaciers⚡#polar⚡#microbiology⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

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