Установить свойства виджета в 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
A rustic handmade ceramic mug filled with rich hot chocolate, topped with melting marshmallows and a dusting of cocoa powder. The mug sits on a weathered wooden table beside an open book and a softly folded knitted blanket. Gentle morning light filters through a window, creating soft shadows and highlighting the steam rising from the drink. Cozy, atmospheric mood, hyper-detailed, shallow depth of field, 8k resolution, warm tonal palette, lifestyle photography, no text or logos visible. --ar 3:4 --v 7
#food
📣Midjourney prompts
Нужно почаще делать. Крайне рекомендую 👍🏼
isometric photography of delicious baguette sandwich lay on flat ground in studio, it contain (lettuce, sliced tomato and cucumber and salami sausage, melted cheese), solid dark red background, white studio lighting, minimalistic product photography, natural color and lighting, 80mm shot, high resolution --ar 2:3 --v 7
#food
📣Midjourney prompts
An ultra-realistic photograph of the Mocha coffee cocktail in its signature glass, with layers of cream and caramel on top. The drink is placed on a wooden tray surrounded by scattered brown coffee beans. In front of it lies one small bowl filled with espresso. Soft lighting highlights the texture of each element, creating a warm atmosphere that suggests comfort without overwhelming attention to detail --v 6.1 --ar 71:128
by queen4497
#food
📣Midjourney prompts
Ultra-realistic, 8K, highly detailed cinematic shot of tiny humanoid workers (6 inches tall) struggling to transport a massive pomegranate on a miniature wooden truck. Some tiny workers push the giant fruit up a ramp, while others tie tiny ropes to secure it in place. The mini truck's wheels sink slightly under the fruit’s weight, showing the immense size of the pomegranate. A tiny driver sits inside the miniature truck cabin, steering carefully as the vehicle moves down a narrow dirt road surrounded by lush trees. The background features more tiny workers following the truck, carrying baskets of smaller pomegranates. Photorealistic lighting, cinematic depth, and immersive storytelling. 8k --ar 9:16 --v 6.1
by thetrailerspk_66832
#food
📣Midjourney prompts
A highly realistic advertising scene featuring a plastic cup with a straw, for decoration, on the rim is two leaves green of brown sugar. .The upper section of the cup is filled with fresh jus green tea green matcha and coco liquid with vanilla. The middle section contains a smooth, slushy iced drink made from a blend of liquid of green tea green matcha , The bottom section of the cup features A realistic scene of bubbles black café boba. This plastic cup is surrounded by a Half a piece of coconut with its green leaves, and on the other side of the plastic cup, a purple jasmine flower, and the scene is presented in an advertising and professional manner. . The entire scene is captured using professional advertising techniques and a high-quality camera, delivering a visual presentation with the highest level of realism. The background is an attractive pink shade --v 6.1
by khabbaz
#food
📣Midjourney prompts
A lavish macro picnic scene with a wicker basket filled with freshly baked baguettes, arranged beside a silver fruit tray holding pomegranates, pears, and grapes. The fruits' vibrant colors contrast against the ruby red blanket, while scattered rose petals and lavender sprigs add a touch of romantic charm. The vibrant red trees in the background create an opulent autumn backdrop, bathed in soft, warm light. Captured in high-definition photography, emphasizing textures, colors, and natural elegance --ar 3:5 --v 6.1
by newyrok1976
#food
📣 Midjourney prompts
A bowl of chicken and vegetable soup with green oil, in front of which is a colorful fabric --v 6.1 --ar 21:32
by queenbee_67685
#food
📣 Midjourney prompts
Create a vivid, high quality image on a white background of the following items on a plate: chocolate, grapes, onions, garlic, avocado, citrus, coffee, macadamia nuts, and walnuts --v 6.1 --ar 2:3
by hoot2055
#food
📣 Midjourney prompts
Create a cinematic fairytale-style photo project showcasing an entire city made from Mamaliga (polenta), inspired by the traditional Orheiul Vechi landscape. The scene features enchanting hills crafted from the vibrant yellow texture of Mamaliga, with rivers of liquid sour cream winding through the terrain. The city is alive with whimsical details: trees formed from delicate slices of garlic and charming houses built from soft cottage cheese. Natural colors enhance the realism, with diffused sunlight softly highlighting every texture, creating a vivid, magical Moldovan atmosphere that balances realism with a fairytale-like wonder. Format the image in 9:16 ratio for reels, capturing the vertical majesty of the landscape --v 6.1
by kate12131415
#food
🔱 Prompt collection
Blueberry milkshakes in a round serving glass table background , side ANGLE full glass view clear composition on light wooden table background, bright daylight, on the middle of the table the style of Hasselblad X2D, following rule of third, vibrant color, no blur --s 50 --v 6.1
by azzholk007
#food
🐝 Prompt collection