Установить свойства виджета в 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
Green University Organized “Youth Day” Events
On April 16, in celebration of Youth Day, Green University organized a series of events covering various areas for students and young people.
🖥The program included psychological consultations, English language classes, sports competitions, and the “Zakovat” intellectual game. In addition, a preventive awareness session with representatives of the internal affairs bodies was held, followed by an open Q&A session on legal topics.
#GreenUniversity#YouthDay#StudentLeague
👉ReadMore ___________________
Green University’da “Yoshlar kuni” tadbirlari o‘tkazildi
16-aprel “Yoshlar kuni” munosabati bilan Green University’da talabalar va yoshlar uchun turli yo‘nalishlarni qamrab olgan tadbirlar tashkil etildi.
🖥Dastur doirasida psixologik konsultatsiyalar, ingliz tili mashg‘ulotlari, sport musobaqalari hamda “Zakovat” intellektual o‘yini o‘tkazildi. Shuningdek, ichki ishlar organlari vakillari ishtirokida profilaktik uchrashuv va huquqiy mavzudagi ochiq savol-javob sessiyasi tashkil etildi.
#GreenUniversity#YoshlarKuni
👉Batafsil
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
Highlights from the Youth Day at Green University.
#GreenUniversity#YouthDay#StudentLeague#TeamSpirit#Leadership
__________________________
Green University Yoshkar kunidan lavhalar.
#GreenUniversity#YoshlarKuni#TalabalarLigasi#TalabalarHayoti#Jamoaviylik#Liderlik
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
📌On April 9, Green University actively celebrated Youth Day with a dynamic and engaging program that brought together students, faculty, and administration.
🗣️Throughout the day, participants took part in a wide range of activities — from educational workshops and intellectual games to open lectures and cultural events. The atmosphere was vibrant, reflecting the energy, enthusiasm, and ambition of the youth.
A special highlight was the opening of the Student League sports competitions, where the university rector, Dr. Bakhtiyor Pulatov personally took part alongside students. His participation made the event even more inspiring, strengthening the spirit of unity, teamwork, and friendly competition.
✅Youth Day at Green University once again proved that the university is not only a center of education, but also a space where students actively develop, engage, and succeed together.
#GreenUniversity#YouthDay#StudentLeague#StudentLife#TeamSpirit#Leadership
👉ReadMore __________________________
📌9-aprel kuni Green University'da Yoshlar kuni keng qamrovli va mazmunli dastur asosida faol tarzda nishonlandi. Tadbirlar davomida talabalar, professor-o‘qituvchilar hamda universitet rahbariyati birlashdi.
🗣️Kun davomida ishtirokchilar turli ta’limiy seminarlar, intellektual o‘yinlar, ochiq ma’ruzalar va madaniy tadbirlarda faol qatnashdilar. Muhit yoshlarga xos energiya, ishtiyoq va intilishlarga boy bo‘ldi.
Tadbirning eng esda qolarli biri Talabalar ligasi sport musobaqalarining ochilish marosimi bo‘ldi. Unda universitet rektori, professor Baxtiyor Pulatov ham talabalar bilan bir qatorda ishtirok etib, o‘zining faol ishtiroki orqali birlik, jamoaviylik va sog‘lom raqobat muhitini yanada mustahkamladi.
✔️Green University'da Yoshlar kuni yana bir bor universitet nafaqat ta’lim maskani, balki talabalar har tomonlama rivojlanadigan, faol ishtirok etadigan va birgalikda yuksaladigan muhit ekanini namoyon etdi.
#GreenUniversity#YoshlarKuni#TalabalarLigasi#TalabalarHayoti#Jamoaviylik#Liderlik
👉Batafsil
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube