Установить свойства виджета в 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 highland climate zone, found on tall mountains and plateaus, can create pockets where tropical, temperate, and even polar conditions exist within just a few vertical kilometers. ✨
#climate⚡#elevation⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some cities, like Johannesburg, are built on high plateaus called "highveld," sitting over 1,700 meters above sea level. Their altitude shapes local climate and city life in unique ways. ✨
#urbanization⚡#elevation⚡#climate⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Mount Everest isn’t Earth’s tallest mountain from base to peak—that title goes to Hawaii’s Mauna Kea, which rises over 10,000 meters from deep ocean floor to summit, out-towering Everest by far. ✨
#mountains⚡#volcanoes⚡#elevation⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The tallest volcano on Earth is Mauna Kea in Hawaii. Measured from its base on the ocean floor, it rises over 10,000 meters—making it taller than Mount Everest from base to summit. ✨
#mountains⚡#volcanoes⚡#elevation⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The first known use of contour lines on a map appeared in 1584, showing the depth of water in the Netherlands. This method is still used today to show elevation and terrain on modern maps. ✨
#cartography⚡#elevation⚡#history⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Mount Chimborazo in Ecuador is the farthest point from Earth’s center, not Mount Everest. Its location near the Equator means it sits atop the planet’s equatorial bulge. ✨
#coordinates⚡#equator⚡#elevation⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Cartographers use colors on maps to represent different heights—this is called hypsometric tinting. Lighter colors usually show higher land, while darker tones indicate lower elevations. ✨
#cartography⚡#elevation⚡#colors⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
B U B B L E H O U S E / Cheng Dong. A coherent city / Sangu Design
The Human Condition by Hannah Arendt says that world is like a table that brings people together and separates people from each other. People yearn to see each other in the city; they call for a new connection which is beyond age, experience, boundaries, it also can transcend personal loneliness and urban barriers.
.
When the architect design and construct from the perspective of the user, they therefore are willing to respect the vitality of the building and rationally make use of the existing rules and conditions to practice the possibility of the local urban lifestyle.
#facade#elevation#interior#urbanplan#geometricarchitecture#glassfacade#interiordesign#composition#modulararchitecture#building#arch_shovel
Дорогие Леди! С нашим праздником Вас!🖤
Дорогие Джентельмены, поздравляем Вас с тем, что Мы есть у Вас такие праздничные!
😂😜❤️🔥💡🔌🧨💣
Photobombed & reels by @hristy__
Кристюша спасибо за то,как ты умеешь видеть женщин!❤️🔥
MUAH by @elena__muah
Леночка,спасибо!В твоих руках мы становимся Богинями!Каждая!❤️🔥
#8марта#спраздником#девочки#женщины#бабушкитожедевушки#нашдень#girls#girlswannahavefun#moodoftheday#photooftheday#reels#lady#actress#model#blackpink#blackdress#мирославакарпович#мира#petitefashion#womensfashion#retro#elevation#elegance#petitefemme#mira#женщинамира
С ВЕСНОЙ ВАС🤍🕊️✨
#highlevel#newchapter#goldenedition
Photobombed me @hristy__🧨
Makeup & hair @elena__muah💋
#muse#яработаюмузой#actress#actrice#model#legslegslegs#elevation#higher#postcard#spring#springspringspring#springfashion#moodoftheday#photography#photooftheday#lady#mademoiselle#purelove#heavenonearth#благодарю#люблю#свеснойвас#доброеутро#petitefemme#mira#женщинамира#карповичмирослава