Установить свойства виджета в 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 sunrays taking;
All the darkness away,
Love taking all hatred away,
Miniature hopes in shapes of stars,
Now subsiding in beautiful destiny,
Happiness taking all the pain away.
In midst the beautiful world,
I laid here,
Breathless,
My sould taken away by you,
My heart given to beat in someones
Else's cage,
My body drifted with fire,
My voice taken away by deafening silence,
My memories now, washed away,
Fading away with new ones.
This is how,
A beautiful day began,
Changing my life,
To be dreadful forever,
In midst the beautiful world,
I laid here as a dead lover.
#tyler#review
She's like a poem,
Waiting to be read.
She's like a song,
Waiting to be sung.
She's like a melody,
Waiting to be heard.
She's like a book,
Waiting to be understood.
She's like a dance,
Waiting to be performed.
She's like a beauty,
Waiting to be cherished.
She's like art,
Waiting to be crafted.
She's you,
Waiting to be found.
She's you,
Waiting to be loved.
She's not just a girl,
She's within all of you,
She resides somewhere inside,
Somewhere the golden rays don't reach,
Somewhere the silver shine doesn't work,
Somewhere in you,
She stays,
Waiting to be acknowledged.
#tyler#review
She's like a poem,
Waiting to be read.
She's like a song,
Waiting to be sung.
She's like a melody,
Waiting to be heard.
She's like a book,
Waiting to be understood.
She's like a dance,
Waiting to be performed.
She's like a beauty,
Waiting to be cherished.
She's like art,
Waiting to be crafted.
She's you,
Waiting to be found.
She's you,
Waiting to be loved.
She's not just a girl,
She's within all of you,
She resides somewhere inside,
Somewhere the golden rays don't reach,
Somewhere the silver shine doesn't work,
Somewhere in you,
She stays,
Waiting to be acknowledged.
#tyler#review
During a dreadful night,
I managed to put up a fight.
Maybe the strong me died,
And weak me survived.
The constant voices in my ears,
Here I am living in my fears.
Like a painful reminder of that night,
Where I lost a outnumbered fight.
Wondering if I am even right,
While holding myself tight.
The night is long dead,
Here my tears still wetting my bed.
That dreadful night,
The cause of my fright.
These thoughts make me shiver,
The fear making me quiver.
My painful screams,
Still haunting my dreams.
Maybe the strong in me died,
And weak me survived.
I haven't given up the fight,
Because I know,
I can still make it right.
#tyler#review
The correspondence of Tyler Robinson, a suspect in the murder of Charlie Kirk, with his transgender lover, with whom he lived, has been published. The name of the roommate is not mentioned.
#correspondence#tyler#robinson#suspect
#Trump#Democrats
👂More on Trump's Ear ⚠️