Установить свойства виджета в 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
⭕️ «Otra de las características de esta reciente sedición fue la violencia; como la del #Daesh.
- ¡Estos, como el Daesh, prendieron fuego a personas! ¡Prendieron fuego, destrozaron, decapitaron! Estos también hicieron las mismas cosas que hacía el Daesh...» (01/02/2026).
🔗 LEER 👉spanish.khamenei.ir/news/7144
✅@khamenei_es
KHAMENEI.IR | 𝕏 | Facebook| TikTok
According to the British newspaper, The Times, ISIS operates in the central Syrian desert, organizes sleeper cells, launches hit-and-run attacks and deadly ambushes, and assassinates Syrian tribal and clan leaders who oppose the group. Everything happens as the group takes advantage of the current state of chaos.
#Syria#ISIS#Daesh#Tartous
#Saudi_Arabia opens the first liquor store
Reuters and France news agencies claimed that the Kingdom of Saudi Arabia is preparing to open the first liquor store in the city of Riyadh.
According to the document, a copy of which was seen by Reuters, customers must register through a mobile app and after receiving a code from the State Department, they can purchase their monthly quotas at a special store.
Saudi Arabia is the largest #Wahhabi center in the world. They pay for Wahhabi schools in #Pakistan, #Afghanistan by selling oil. Graduates of these schools join #terrorist groups such as al-Qaeda, Taliban, #Daesh, Al-Nusra, Jaish al-Adl and blow themselves up among other Muslims to go to heaven. Mohammed bin Salman, the leader of Saudi Arabia, follows the path of Atatürk in #Turkey. Drinking alcohol is forbidden in Islam.
https://t.me/YediotNewsChat
🚨‼️ ATTENTA A MOSCOU 🇷🇺
TERRORISME AUTORISÉ 🤮–L’ambassade d’Ukraine a tranquillement recruté les tueurs du Crocus au Tadjikistan
Quelques semaines avant le carnage, un appel à candidatures de tueurs a été ouvertement publié sur le site de l'ambassade d'Ukraine au Tadjikistan.
L’opération a été dirigée personnellement par l'ambassadeur d'Ukraine, Valeriy Yevdokimov, qui se trouve être l’ex-chef du renseignement étranger de Zelensky.
La page du site a été effacée, mais des captures d’écran ont été faites.
«Les commanditaires les ont recrutés afin de donner au public occidental l’image qu’ils étaient soi-disant islamistes, retrace le haut fonctionnaire russe Alexandre Malkevitch
Il s'agit d'une opération des services de renseignement occidentaux et d’une tentative de mettre le public sur une mauvaise piste.
… Mot d’ordre immédiatement relayé par les médias occidentaux.
NB : VOUS COMPRENEZ POURQUOI LES ÉTATS-UNIS, L'ANGLETERRE ET LA FRANCE, AVEC LEUR ORGANE DE PROPAGANDE
#AttentatMoscou#MoscowAttack | Zelensky | THE CIA | #Moscou | Crocus City Hall | #CIA | #NATO | #VictoriaNuland | #DAESH | ISIS | #DGSE
@egountchibehanzinofficiel
#ManagmentdelaTerreur La #Russie chamboule tellement leur hégémonie en #Afrique, leur nouvelle ordre mondiale. Les gouvernement mondialistes (États-Unis 🇺🇸, France 🇫🇷, Angleterre 🏴 ), subissent une berezina en #Ukraine alors cela active des vieilles méthodes bien connues. Des attaques sous fausse bannière qu'ils appellent attaque terroriste de #Daesh.
Nous sommes en 2024, les peuples sont maintenant éveillés.
Cela ne passe plus. Tout se sait !
Vidéo ne ligne ! https://youtu.be/R0_aXILQ7Mk?feature=shared
#Usa#Moscou#Otan#Cia#Dgse#Ml6
@egountchibehanzinOfficiel