Установить свойства виджета в 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
If it’s painful for you to criticize your friends, you’re safe in doing it; if you take the slightest pleasure in it, that’s the time to hold your tongue.
– Alice Miller
#friendship@quietworld🍃
As you get older real friendships don’t mean you see each other everyday. In fact some of the realest friends barely see each other, if you both are really out chasing your bags, tryna better your futures, you probably won’t see each other as often.
#friendship@quietworld🍃
Dear folks, this is a translation of one famous poem of one famous poet into English.
Can you please review it and let me know, if it sounds correct, or does it contain enything weird, odd ?
/********************************************/
I like to feel that I'm not sick with you
I like to know that sickness yours is yours not mine
That heavy ball of earth won’t stray off from its course
Away from our footprints , fading in sunshine
I love that I could funny be
Bewildered, clumsy , not wordplaying
not turning red upon sleeves touching game
not turning pale when see you on your knees
I love to see you hugging someone else
Before my eyes , reposefully and calmly
Not sending me to fire glowing hell
To burn forever for not kissing me , my darling
I like that mentioning my name is not your habit
That tender name you don't utter day-and-night in vain
That no one's gonna sing Hallelujah on our wedding
In silence of the church, one sunny autumn day
Thank you for love, with all your heart and soul
That brings me peace at night, unconscious, unaware
Thank you for rare meetings if at all
So nice, That never in the moonlight do we stroll
So great that sun warms not us, soaring high elsewhere
So pity, that I am not sick with you
So bad, that sickness yours is yours not mine
#review
#friendship