Установить свойства виджета в 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
⚠️ ATTENTION ATTENTION! ⚠️
Gamety's very first X Podcast is here! 😮
We've been talking about #Gamety for some time. But some of you may still be wondering: "What is Gamety?" 😃
Set a reminder on your calendar!
Time: May 22, 2024, at 3 PM CET.
Venue: X Space
It's time to find out about us! 📈
Tweet 🔗:
https://x.com/gametyio/status/1792968517047988521
🖇 Important Links:
Website | X | Chat | Discord | Announcement | Youtube
For those of you who love engaging with Gamety's social media channels, we have a token of appreciation for you!
Join our Post-To-Airdrop program for a chance to win big from our massive 5,000,000 $GTY token pool! 💰
To participate:
1️⃣ Repost our announcement with #Gamety; @gametyio; and $GTY
2️⃣ Follow @gametyio
3️⃣ Promote for max engagement
More reach = Higher rank on @keani_gg Leaderboard!
Read more: https://keani.gg/gamety
Tweet 🔗:
https://x.com/gametyio/status/1789481845626667017?s=46
🖇 Important Links:
Website | X | Chat | Discord | Announcement | Youtube
👊Punch-to-Earn Airdrop👊
🏅Airdrop Prize Pool: 8,000,000 $GTY
Link: t.me/GametyApp_bot
Calling all gamers!
Who loves to punch someone in the face and earn some money from it?.👊💥
Inspired by the success story of @thenotcoin, Gamety brings tap gaming to the next level!
Invite friends to #Gamety's Telegram, rack up points & climb the leaderboard NOW! 🏆
🔗Tweet:
https://x.com/gametyio/status/1788666261288763550?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
Bitcoin halving has been finally took place, cutting mining rewards to 3.125 BTC .
The new era of Bitcoin is starting, and #Gamety is here to ride the wave!
🔗 Tweet:
https://x.com/gametyio/status/1781498935594622998?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
🎉 We're thrilled to announce our partnership with MetaMuffin!🚀
As KOLs in the Web3 space, they'll be helping us spread the word about #Gamety's revolutionary gaming platform on Runes Protocol
Join us on this exciting journey together! 🕹✨
🔗 Tweet:
https://x.com/gametyio/status/1781371957512171916?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
Innovation is at the heart of #Gamety’s P2E model.
Explore our cutting-edge game mechanics that redefine entertainment. 🕹️
Be our early members by joining our community now!
🔗 Tweet:
https://x.com/gametyio/status/1780368302159901131?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
Learning meets leisure at #Gamety.
We're discussing educational content in Gamety’s socials to enrich our gaming ecosystem. 📚
What Web3 concept would you like to learn with us? 👀
Join our community to find out more!
🔗 Tweet:
https://x.com/gametyio/status/1779933725146640751?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
The #Gamety marketplace is where gaming meets commerce.
Trade in-game assets with ease and security on our platform. 🛍️
Let’s get your way to the top!
🔗 Tweet:
https://x.com/gametyio/status/1779575482679525580?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
🌙 Eid Mubarak to all celebrating around the world!
May this special day bring peace, happiness, and prosperity to everyone.
From #Gamety, with love 💕
🔗 Tweet:
https://x.com/gametyio/status/1778046881060503747
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
Tokens that do more!
Find out how $GTY fuels the #Gamety ecosystem, powering rewards, and in-game purchases.
Join our community to learn more!
🔗 Tweet:
https://twitter.com/gametyio/status/1777453037226991772?t=y7r0-4TMHMOkDvjPyXEolg&s=19
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
At #Gamety, every pixel is crafted with the player in mind. 😎
Want to be involved more as early members?
Our user-centric approach will be setting new standards in gaming experience! 🔲
Join our community now! 🚀
🔗 Tweet:
https://x.com/gametyio/status/1777063704519180769
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
It is our pleasure to announce the DCI Capital as one of our investors in the Private Round! 🚀
Together, we can develop #Gamety as the revolutionary gaming platform for Bitcoin ecosystem! 🔲
🔗Twitter
https://x.com/gametyio/status/1775574940139581593?s=20
🖇Important Links:
Website | X | Chat | Announcement | Youtube