Установить свойства виджета в 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 presence of 4 thousand French soldiers in the Gaza war
Thomas Bourtes, a member of the #French parliament, announced that more than 4,000 French citizens are participating in the Israeli army in the war against Gaza.
La présence de 4 mille soldats français dans la guerre à Gaza
Thomas Bourtes, député français, a annoncé que plus de 4 000 citoyens français participent à l'armée israélienne dans la guerre contre Gaza.
https://t.me/YediotNewsChat
Еще одна полезная рекомендация для french learners:
https://youtube.com/playlist?list=PLycTNLUo2y2EAKEhVfxB9gYo6r0OTMgM0&si=SBoZIA4aZQhFpzMl
Очень классный подкаст, легко понять и даже есть транскрипт, если слушать на сайте
#french
Я довольно неплохо понимаю текста, которые читаю на французском и после этого фото поняла почему😆
Но я понимаю, что словарный запас надо расширять, поэтому решила, что буду больше читать. С английским было так же, больше всего слов я выучила после фокуса на чтение
#french
#Rap#French
Manau le curé et les Loups
It speaks of a priest guarding a village against a wolf pack, the priest speaks of his regrets and the things he would have liked to do in his life.
In the end, as the sun clears the night, the villagers find the priest dead, killed by the wolves as he was protecting the village.
https://youtu.be/UEpzez_H2CI
After calling the #Hijab “a symbol of women’s submission to men”, #French Interior Minister continues his #Islamophobic comments, calling the Hijab “a sign of inferiority.”
#Op_ed: #Djibouti: Pillar of stability, not a "rentier fortress" in decline
In a rebuttal to an op-ed titled "Crumbling of Rentier Fortress: Ethiopia’s Maritime Pivot, Decline of Djibouti’s Monopoly," Naguib Ali Taher, Communications Officer for the Republic of Djibouti, firmly rejects the characterization of his nation as a “crumbling rentier fortress.” He dismisses the portrayal as both “inaccurate and dismissive,” arguing that it misrepresents the geopolitical reality of the Horn of Africa.
Taher contends that Djibouti remains “an undeniable bedrock of stability” within a volatile region—a status validated by the presence of major #American, #French, #Chinese, and #Japanese military installations.
The author further brushes aside accusations of authoritarianism and regional meddling, labeling them "tabloid-style slander."
https://addisstandard.com/?p=55291
#Vocabee#Snap#amp#Learn#French
Join the Vocabee: Snap & Learn French beta on ✈️#TestFlight
🔗 Link: https://testflight.apple.com/join/tAwWnF8e
Shared by Dimitri