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

Резултати

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

Пребарај: #volcano

当前筛选 #volcano清除筛选
Interesting Planet 🌍

@interesting_planet_facts · Post #1294 · 15.02.2026 г., 12:11

🌎 On August 24, 79 CE, Mount Vesuvius erupted violently, burying the Roman cities of Pompeii and Herculaneum in volcanic ash. This sudden eruption killed thousands and preserved entire towns under meters of ash, offering archaeologists rare insight into daily Roman life. ✨ #volcano⚡#archaeology⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1079 · 27.11.2025 г., 22:11

🌎 In 1816, a year after the Tambora volcano erupted in Indonesia, much of the world experienced a “Year Without a Summer.” Temperatures dropped globally, causing widespread crop failures and food shortages. Snow fell in June in parts of North America and Europe, and some regions lost up to 75% of their harvests. ✨ #volcano⚡#climate⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1333 · 08.03.2026 г., 12:11

🌎 A massive volcanic eruption at Lake Toba in Indonesia about 74,000 years ago was one of Earth’s largest known explosions. The eruption released so much ash that it may have triggered a global volcanic winter, cooling the planet and affecting early human populations. Its crater now forms Lake Toba, the world’s largest volcanic lake at about 100 kilometers long. ✨ #volcano⚡#catastrophe⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #803 · 23.09.2025 г., 18:11

🌎 The 1902 eruption of Mount Pelée on Martinique destroyed the city of Saint-Pierre within minutes, killing over 28,000 people. It is the deadliest volcanic disaster of the 20th century. ✨ #volcano⚡#catastrophe⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #770 · 17.09.2025 г., 20:22

🌎 The Toba supereruption in Indonesia about 74,000 years ago was one of the largest volcanic events in the last 2 million years. It ejected 2,800 cubic kilometers of material, triggered a global volcanic winter, and may have caused a dramatic human population decline, as shown by genetic studies indicating a bottleneck in human evolution. ✨ #volcano⚡#history⚡#catastrophe 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #736 · 12.09.2025 г., 18:22

🌎 The 1883 eruption of Krakatoa was one of the most violent volcanic events in recorded history. It unleashed explosive blasts heard 3,000 kilometers away, generated giant tsunamis, and ejected ash high into the atmosphere—causing global temperatures to drop and vivid sunsets worldwide for years after. ✨ #volcano⚡#catastrophe⚡#history 👉subscribe Interesting Planet ​

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