Установить свойства виджета в 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
Language Learning Courses 📕
This section updates daily (some courses may expire fast), so save it and check it regularly.
You’ll find all kinds of language courses — not just English.
#LanguageLearning#English#Spanish#Learning#Courses
🌟 Exciting News at ADC Educational Institution!🌍✨
We're thrilled to welcome our newest team member straight from Canada! 🇨🇦 Meet Christian Bonk, a seasoned professional with a Band 9 IELTS score. 🎉✨
📚 Ready to elevate your English proficiency?
« ADC » now offers cutting-edge IELTS courses guided by Christian Bonk's expertise. 🌐📝
🗓️ Don't miss out on this incredible opportunity! Whether you're gearing up for academic goals or professional aspirations, ADC has got you covered. Contact us anytime to embark on your language journey with confidence! 🌟🚀
We have classes from morning till evening.
If you have any questions, do not hesitate to contact us I
+998742261078 | +998742281121 |
+998958505111 | +998742276163 |
+998742252536|+998952017878
or write on Telegram @admofadc
#IELTS#LanguageLearning#Education#ADCInstitution#Band9Expertise🌐📚
📚Enrollment is open for the 2025–26 academic year!
⏰24 June | 18:00
Join our Presentation of Russian Language Courses for Adults — meet the teachers and find the perfect program for you:
✨Fundamental Course — from A1 to C1, steady pace (October–June)
⚡️Intensive Course — fast-track A1 to A2, with speaking from day one
🌍Online — learn from anywhere in the world
🏫Offline — full language immersion
👥Group classes — motivation, support & shared experience
👤Individual lessons — flexible schedule, personalized approach
🎉 Plus, learn about our linguistic and cultural events for students!
📅Free participation — sign up via the linkhere
#russianlanguage#learnrussian#russiancourses#languagelearning#onlinelearning
Lesson 19 of my Uzbek self-study course teaches you how to book a table in a restaurant or café in Uzbek. Learn useful phrases, listen to dialogues with audio, and practice with exercises to master real-life situations.
https://yep.uz/en/2025/09/lesson-19-booking-a-table-in-uzbek/
#uzbeklanguage#learnuzbek#uzbeklessons#selfstudy#languagelearning#uzbekdialogues#bookingatable
Lesson 42 is out! Learn how to ask “How much does it cost?” in Uzbek. Practice the most common shopping phrases, short dialogues, and real-life expressions with audio and exercises. Start speaking confidently at the market, in shops, or while traveling in Uzbekistan.
https://yep.uz/en/2025/09/lesson-42-how-much-does-it-cost-in-uzbek/
#learnuzbek#uzbeklanguage#uzbeklessons#languagelearning#howmuch#shoppingphrases#beginneruzbek
Lesson 20 of my Uzbek self-study course with audio is here! Learn how to say countries, nationalities and languages in Uzbek. The lesson includes exercises, tables, a crossword puzzle and clear grammar explanations.
https://yep.uz/en/2025/09/lesson-20-countries-nationalities-languages-uzbek/
#uzbeklanguage#learnuzbek#uzbeklesson#languages#nationalities#countries#selfstudy#languagelearning
Want to learn how to shop in Uzbek? In this new lesson, you’ll discover useful phrases for the bazaar, shops, and buying souvenirs. Listen to the audio, repeat, and practice!
https://yep.uz/en/2025/10/uzbek-shopping-phrases-eastern-bazaar/
#uzbeklanguage#shoppinginuzbek#learnuzbek#uzbekphrases#easternbazaar#souvenirs#languagelearning#uzbeklessons
Lesson 21 of our Uzbek self-study course: digraphs sh, ch and the letter l.
Learn their pronunciation, see examples with countries and nationalities, and practice with audio exercises.
https://yep.uz/en/2025/09/lesson-21-uzbek-digraphs-sh-ch-l/
#uzbek#uzbeklanguage#uzbeklesson#uzbekalphabet#learnuzbek#languagelearning#sh#ch#LeMonde
🎉 IELTS topshirishni xohlovchilar uchun yangilik! 🎉
O'quv markazimizda taniqli o'qituvchi Danila Polikarpov IELTS imtihoniga tayyorgarlik ko'rish uchun guruhlar ochilayotganini mamnuniyat bilan e'lon qilamiz! 💼🌟
Danila bilan siz nafaqat testning har bir qismini ishonchli tarzda engishingiz, balki ingliz tilini o'rganishda shaxsiy maqsadlaringizga erishishga tayyorlanishingiz mumkin! 📚✨
Yangi guruhimizga qo'shilish va IELTS dan yuqori natijalarga erishish imkoniyatini qo'ldan boy bermang! 🚀💯
Savollaringiz bo'lsa biz bilan bog'laning
+998742261078 +998742281121
+998742276163
+998742252536 +998952017878
yoki Telegram @admofadc ga yozing
#IELTSpreparation#Englishexam#studyabroad#Languagelearning#IELTStips#Testpreparation#Englishskills#Examstrategy#AcademicEnglish #IELTSsuccess# Languageproficiency #Studygram #IELTSclass# Examgoals #Testtaking#Englishproficiency#LearnEnglish#IELTSpractice#Testprep#Languageexam