Установить свойства виджета в 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
🇮🇷 Breaking: University protests flare up across Iran
New student protests erupted at major Iranian universities as the new term began, with demonstrators honouring victims of last month’s deadly crackdown. Clashes were reported in Tehran, with chants targeting Supreme Leader Ali Khamenei and reviving the “Woman, Life, Freedom” movement.
The unrest comes amid rising geopolitical tensions, as the U.S. boosts its regional military presence while nuclear talks with Tehran remain unresolved. #News#Iran#University
「💻」#university#studying_tips
new semester, better me 📚🦪.
Yesterday I did a lot of stuff including unpacking and setting up my room for the semester.
Of course I will redecorate it, however I shouldn’t forget that this room is for only one semester
✨
Inshallah will go to study away
😻
~🐈~
↬@jastm1🌊
「💻」#university#studying_tips
❤️Some college x School inspo
✨A new chapter is here!✨
Are you ready for school/college? ✨
This is the perfect time to set new ambitions and new goals. A chance to start fresh, grow, and chase the best version of yourself. 🌱
Don’t be shy, step forward with confidence, give it your best, and make this year unforgettable.💗🫶
~🐈~
↬@jastm1🌊
「💻」#university#studying_tips
Checklist of things to pack for UNIVERSITY🥳!
Most of you might be overwhelmed with the amount of things to do, but don't worry you've got this 💪.
Save not to loose!
~🐈~
↬@jastm1🌊
https://www.coursera.org/specializations/data-science-python?utm_medium=email&utm_source=marketing&utm_campaign=2QBGEJZREeajEnVsu251ig
The 5 courses in this #University of #Michigan specialization introduce learners to data science through the python programming language. This skills-based specialization is intended for learners who have basic a python or programming background, and want to apply statistical, machine learning, information visualization, and text analysis techniques to gain new insight into their data.
Introduction to Data Science with Python (course 1), Applied Plotting, Charting & Data Representation in Python (course 2), and Applied Machine Learning in Python (course 3) should be taken in order and prior to any other course in the specialization. After completing those, courses 4 and 5 can be taken in any order. All 5 are required to earn a certificate.
Bizning faxriy oqituvchimiz Sultanov Ruslan Rustamovich
➖➖➖➖
Наш почётный учитель Султанов Руслан Рустамович
#tiue#university#университет
Telegram | Instagram | Website
Congratulations Class of 2027! Welcome to New Uzbekistan University! 🎉
#NewUU2027#NewUzbekistanUniversity#University
Check out the full video on our YouTube!
Best Regards,
NewUU Student Council
Telegarm | Instagram
🇰🇷Janubiy Koreya ta’lim tashkilotlari bilan hamkorlik aloqalari mustahkamlanmoqda
🇺🇿Batafsil
___
Strengthening cooperation with South Korean educational organizations
🇬🇧Eng
___
Укрепление сотрудничества с Южно-Корейскими образовательными организациями
🇷🇺Ru
#GraduateSchool#Soonchunhyang#University#Cooperation
Web-site | Telegram | Facebook | Instagram
Handong Global universiteti bilan hamkorlikni yangi bosqichlari
🇺🇿Batafsil
___
New Stages of Collaboration with Handong Global University
🇬🇧Eng
___
Новые этапы сотрудничества с Глобальным университетом Хандонг
🇷🇺Ru
#GraduateSchool#Handong#Collaboration#University
Web-site | Telegram | Facebook | Instagram