Установить свойства виджета в 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
🇵🇪#Peru: Former Senate candidate Jorge Luis Alcalde Alfaro was assassinated by a hitman in broad daylight in Trujillo three days ago.
He was about to enter his car when another vehicle pulled up and opened fire. He later died on the way to the hospital.
(📹 via @cartelwatchnet on X & Caretas.pe)
🗺 Peru 🇵🇪
🟠It turns out you can ski not only on snow but also on sand. Such skiing takes place in the Ica Desert in Peru!
This is called sandboarding.
📏
📏
📏
📏
📏
📏
📏
📏
#Peru | @voyage
🗺 Peru 🇵🇪
🟠It turns out you can ski not only on snow but also on sand. Such skiing takes place in the Ica Desert in Peru!
This is called sandboarding
📏
📏
📏
📏
📏
📏
📏
📏
#Peru🇵🇪@voyage
🗺 Peru 🇵🇪
📏
📏
📏
📏
📏
📏
📏
📏
🟠It turns out you can ski not only on snow but also on sand. Such skiing takes place in the Ica Desert in Peru!
📏
📏
📏
📏
📏
📏
📏
📏
This is called sandboarding.
📏
📏
📏
📏
📏
📏
📏
📏
#Peru🇵🇪@voyage
🗺 Peru 🇵🇪
It turns out you can ski not only on snow but also on sand. Such skiing takes place in the Ica Desert in Peru!
This is called sandboarding.
#Peru
@voyage
Peru🇵🇪
Impressive natural masterpiece - the Rainbow Mountains in the Cusco region. ⛰🌈
The colorful layers of these mountains were formed millions of years ago from red sandstone, which, under the influence of climatic conditions, underground water, and mineral impurities, became stained with yellow, green, white, and other colors.
#Peru
@voyage
Peru🇵🇪
A walk with a magnificent view of Machu Picchu.
Machu Picchu is a legendary city nestled in the heart of the Andes at an altitude of 2400 meters. It is an ancient Inca settlement located between two mountain peaks. 🏔
When tourists gaze at the ruins of the city of Machu Picchu, which stand out dramatically among the jungle-covered mountain peaks and steep slopes, and the terraces descending into the valley, their breath is taken away.
#Peru
@voyage
The right to die
#video#Peru
Ana Estrada is confined to bed most of the time and can breathe only with a respirator. She lives with polymyositis, a rare muscle disease with no cure. Since 2016, Ana has been writing a blog called ‘Ana seeks a dignified death’. In addition, she started a legal battle to decide to end her life ‘when the time comes’. Assisted death is illegal in her country of Peru.
Peru is primarily a Catholic country, where euthanasia is prohibited alongside same-sex marriage and abortion. However, in 2021 a court ruled in favour of Ana and cleared anyone assisting in her death of criminal charges. Ana says she would decide to die when she could no longer write her blog.
On this day in 2000, the Dutch lower house of parliament voted to legalise euthanasia. Thus, the Netherlands became the first country that allowed mercy killings. Euthanasia is also legal in Spain, Belgium, Luxembourg, Canada and Colombia.
Follow: https://t.me/rtdocumentary
#video#Peru
Hundreds of thousands of Peruvian women were forcibly sterilised between 1996-2000 as part of President Alberto Fujimori’s family planning programme. The initiative was launched to reduce poverty and cut birth rates among the poor. While it was supposed to be consensual, women involved in the programme say otherwise. Most of the victims came from poor indigenous communities.
Josefa was at home when nurses came and forced her to go to the hospital. She still recalls waking up after the procedure and seeing other women crying out their husbands’ names in pain. In the following years, Josefa suffered from infections and cancer. Decades later, Josefa and others are still seeking justice through a class action suit against the ex-president.
Follow: https://t.me/rtdocumentary
#GASTRONOMIA#PERU🍲 | Cultura, sabor y frescura: La magia de la gastronomía peruana en Déjame Que Te Cuente https://ift.tt/hEqG9Wf March 22, 2025 at 06:00AM
#GASTRONOMIA#VENEZUELA#PERU👩🏻🍳🧑🏻🍳👨🏻🍳 | Chef venezolano triunfa con restaurante peruano en su país: "Necesitaba de la gastronomía de Perú" https://ift.tt/YdZC8u1 August 02, 2025 at 09:15AM