Установить свойства виджета в 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
#nostalgiaMahalladagi 10ta kompyuteri bor kompyuterxona, soati 500 so'm bo'lgan paytlar va bir talay o'yinlar😄
➖➖➖➖➖➖➖➖➖
📍Manzil: [ Kichik halqa yo'li 8A ]
⏰ Ish vaqti: [10:00 dan 20:00]
📞 +998338082030
🔵@Comping_admin
➖➖➖➖➖➖➖➖➖
🔵Telegram📷Instagram🟥Youtube
We have all got our “good old days” tucked away inside our hearts, and we return to them in dreams like cats to favorite armchairs.
—Brian Carter
#happiness#nostalgia#life
@quietworld🍃
💿 The Rise and Fall of the Compact Disc
Having been hit by the rise of MP3 players in the early 2000s, #CD sales nearly halved between 2000 and 2007, which is when smartphones and the first music streaming services emerged to put the final nail in the compact disc’s little round coffin.
#Nostalgia
🚀@PerspectiveIX
🌀 http://prs.pctvix.co/TelegramIX
✨Get ready for a blast from the past! It's Retro Day! 🎮🎶
Mark your calendars for May 18, this Thursday, as we transport ourselves back to the magical era of our childhood. 🌟
Join us for a day filled with nostalgia, colorful retro games, and the iconic music that defined our younger years. 🕹🎵
We've curated an exciting lineup of classic games that will make you feel like a kid again. From Tetris to Domino, there's something for everyone to enjoy! Let's relive those epic gaming moments together. 🎮👾
Don your favorite retro outfits and get ready to immerse yourself in the vibrant atmosphere of our childhood. From neon colors to leg warmers, let's embrace the fashion trends that defined an era. It's time to bring back the style! 👕👖
Date: May 18, Thursday
Time: Whole day
Location: New Uzbekistan University
Spread the word and let's make this Retro Day a celebration of our shared past! See you there! 🎉✨
#RetroDay#Nostalgia#ChildhoodMemories
Best Regads,
Student Government.
First Love Should Be Forever... Right? 💔#shorts#cinema#firstlove#loveforever#heartbreak#romance#relationships#emotions#cinematic#lovequotes#drama#nostalgia#movingon
https://pdmovies.substack.com/p/the-big-combo-1955
L'attaccamento agli oggetti é uno degli ostacoli maggiori per la nostra felicità, come se infondessimo in essi parte della nostra anima.
#vaporonda#vaporwave#vapourwave#vaporart#seapunk#webpunk#glitch#glitchart#glitchartistscollective#chillwave#aesthetic#vaporwaveaesthetic#vaporwaveaesthetics#malinconia#melancholy#tristezza#sadness#sadboy#lofi#disagio#nostalgia#illusione#illusion#windows95#windows98#windowsxp