Установить свойства виджета в 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
#Explosion reported in #Mekelle; Officials say no casualties
An explosion occurred late Thursday in Mekelle near the Social Science campus of Mekelle University, though officials say there were no casualties or property damage.
Redahegn Feseha, head of the Mekelle Peace and Security Bureau, told local radio that the blast happened at around 9:30 p.m. near the upper gate of the city’s business campus. He described the incident as a deliberate act aimed at creating fear rather than causing harm, urging residents to remain calm and to condemn what he called an “act of terror.”
Residents reported a mix of fear and confusion. “I was sitting with my family when we heard a loud bang. My kid and my wife were terrified,” said one resident. Another added, “At first, we thought it was a drone attack or something falling. But later we heard it was a bomb.”
https://www.facebook.com/share/p/19x2dWByCq/
🇨🇳Le bilan de l’explosion dans une usine de feux d’artifice en Chine s’est alourdi à 21 morts et 61 blessés, a rapporté la Télévision centrale de Chine.
#chine#explosion
🇨🇳 Une explosion s’est produite dans une usine de feux d’artifice en Chine, faisant 3 morts et 25 blessés, a rapporté l’agence Xinhua.
Vidéo: My Fair Lady/X
#chine#usine#explosion
🇮🇷🇮🇱🇺🇸 Plusieurs civils ont été tués dans l’explosion de mines dissimulées dans des boîtes de conserve, larguées par des avions américains et israéliens près de la ville de Chiraz, dans le sud de l’Iran, rapporte l’agence Tasnim.
#iran#explosion#bilan
🇺🇸Cinq personnes ont été blessées à la suite d’une explosion de gaz dans une église de Boonville (État de New York), a rapporté la chaîne CBS News.
#étatsunis#église#explosion
🇨🇳 Une explosion s’est produite dans une usine de feux d’artifice en Chine, faisant 3 morts et 25 blessés, a rapporté l’agence Xinhua.
Vidéo: My Fair Lady/X
#chine#usine#explosion
🇬🇧 En Irlande du Nord, un homme a été arrêté après l'explosion d'une voiture devant un commissariat de police. Des perquisitions sont en cours à plusieurs adresses de Belfast, indique un communiqué de la police régionale.
#royaumeuni#voiture#explosion
🇦🇪Une explosion a eu lieu dans un immeuble du centre financier international de Dubaï, aux Émirats arabes unis, a rapporté le commentateur politique Mario Nawfal sur le réseau social X.
#émirats#explosion#immeuble
🇬🇧 Un obus non explosé de la Seconde Guerre mondiale a été neutralisé par une explosion contrôlée dans la ville de Plymouth, dans le sud-ouest de l'Angleterre. La BBC a diffusé une vidéo de l'explosion.
La bombe aérienne allemande SC250, une bombe à explosion pesant environ un quart de tonne, a été découverte le 30 avril par un propriétaire qui creusait une tranchée sur son terrain dans le quartier de Southway. La zone a été bouclée et les habitants de près de 1.200 maisons avoisinantes ont dû évacuer leurs domiciles.
#royaumeuni#explosion#obus
🇧🇮 Des dizaines de personnes ont péri dans l’incendie provoqué par des explosions survenues dans un dépôt de munitions à Bujumbura, la capitale économique du Burundi, a rapporté l’Agence France-Presse (AFP).
#burundi#explosion#incendie#victimes