Установить свойства виджета в 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
🌍 The lithosphere’s tectonic plates move slowly, but sometimes collide to form tall mountain ranges like the Himalayas, linking Earth's rocky shell to the atmosphere and biosphere. ✨
#lithosphere⚡#tectonics⚡#mountains⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The biosphere reaches from deep ocean trenches to high mountain peaks, supporting life almost everywhere—even microbes live in extreme environments far below Earth's surface or high in the clouds. ✨
#biosphere⚡#lithosphere⚡#atmosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The biosphere is found in surprising places—microbes thrive in clouds high in the atmosphere and deep within the lithosphere’s rocks, connecting all Earth’s spheres in unexpected ways. ✨
#biosphere⚡#lithosphere⚡#atmosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The lithosphere, atmosphere, hydrosphere, and biosphere constantly exchange matter—volcanic eruptions can shoot minerals into the air that later fall into oceans, nourishing marine life far away. ✨
#lithosphere⚡#atmosphere⚡#hydrosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 When huge dust storms sweep across deserts, fine particles from the lithosphere reach the atmosphere, circle the globe, and even fertilize distant rainforests—linking Earth’s spheres in invisible ways. ✨
#lithosphere⚡#atmosphere⚡#hydrosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 A single major volcanic eruption links all of Earth’s spheres—rock and magma from the lithosphere, gas and ash in the atmosphere, water vapor in the hydrosphere, and rapid changes in the biosphere. ✨
#lithosphere⚡#atmosphere⚡#hydrosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🧠 Building intelligent foundations for Web4.
Lithic enables AI-native smart contracts — combining intelligent execution, programmable logic, and decentralized coordination in one unified layer.
From verifiable AI workflows to scalable infra, this is the next evolution of onchain systems.
Read more 🔍https://lnkd.in/gsez6_GK
Post 🔍https://www.linkedin.com/posts/kaj-labs_lithosphere-lithic-artificialintelligence-activity-7442707365570916352-XBZX/
Website 🌐https://lithic.at/
#Lithosphere#Lithic#Web4#AI#Crypto
🌍 The hydrosphere holds less than 0.01% of Earth's water in rivers and lakes, while most is locked in glaciers, ice caps, or underground. These hidden reserves link all of Earth’s spheres. ✨
#hydrosphere⚡#lithosphere⚡#biosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The deepest part of the ocean, the Mariana Trench, reaches nearly 11,000 meters below sea level. Here, the hydrosphere, lithosphere, and biosphere all meet in extreme conditions. ✨
#hydrosphere⚡#lithosphere⚡#biosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The deepest point on land, the Dead Sea Depression, lies about 430 meters below sea level, linking the lithosphere, atmosphere, hydrosphere, and biosphere in an extreme environment for life. ✨
#lithosphere⚡#hydrosphere⚡#biosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Some bacteria and fungi live deep in rocks of the lithosphere, far below where sunlight reaches. These life forms connect the biosphere to Earth's rocky layer in ways once thought impossible. ✨
#lithosphere⚡#biosphere⚡#microbes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Earth’s spheres aren’t fixed—they overlap at microbe level. Extremophiles, tiny life forms, live deep underground rocks, linking the biosphere to the lithosphere in some of Earth's harshest zones. ✨
#lithosphere⚡#biosphere⚡#microbes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍