Установить свойства виджета в 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
🤩1,000,000 Users in Gamety's Telegram App! 👍
Celebration prize: 250$
Show your love in comments on the Tweet, tag 2 friends and post your BNB wallet. 🔥
This massive milestone is just the beginning, so join the excitement and earn your share of 17.5 Million $GTY 💎 tokens with our gamified Airdrop campaign!
➡️ Go to @GametyApp_Bot now!
Next Step…bring our user #onchain👍
Stay tuned for more big news!
Tweet 🔗:
https://x.com/gametyio/status/1795435819529802165
📎Important Links:
Website | X | Chat | Discord | Announcement | Youtube
⚖️Unlock the advantages of advanced onchain analytics with 10 Bonus Free Days exclusively for Multichain Score holders!
Partnering up with ArbitrageScanner, an ecosystem of #onchain analysis and #cryptocurrency arbitrage products, to deliver more meaningful degen experience for the folks with solid onchain reputation 💪
P.s. ArbitrageScanner is already powering the Nomis Leaderboard—check it out to see how it works!
👇Click the button below to check the offer details and claim your Free Days on available subscriptions!
💠Nomis tApp | X | Discord | YouTube | Check Scores⚖️
🚨MVB 8 Celebration Campaign IS NOW LIVE!
For sure, the smartest move to leverage your brand-new BNB Rep Score which has just launched on BNB Chain by #Binance⚡️
Proud to become a part of BNB Chain ecosystem and share this milestone with YOU in our new campaign linked to our participation in the Accelerator!
🗓1-WEEK duration:
💵Unlimited reward pool starting at $5K
🌱10+ BNB Chain Eco projects w/ perks
❗️ The Score determines your profit! Explore partner planets, complete tasks, and claim your well-deserved rewards — it's that simple!
Your #BNB Score is a power — cause its all about your #onchain reputation on BNB Chain 🌐
Get it, Leverage it, Be Rewarded for holding it 💜
And Stay Tuned for Next Thrilling News 🫵 (We're preparing another cash giveaway 🤑)
🎉 Hello, 2025, from SpotOnChain!
Thank you for an incredible 2024. Big things are coming this year, including the launch of our AI-powered trading agent and the highly anticipated $SOCAI token. 🚀
Here’s to redefining your crypto journey together in 2025! 🥂
#OnChain#SpotOnChain#SOCAI
$ONSING ~ the protective big brother of $PUNCH 🛡️🔥
Solid structure.
Higher highs.
Clean continuation.
Early participants secured partials and continue to ride the trend.
This token builds sustainably, not just pumps.
3AZAjwZZCe8Jf4yccheZ5Z1c2SPEPyoYJHFT3Le2pump
Big brother energy.
#Memecoins#Solana#Crypto#OnChain#Teslacalls🚀
Create/Import your #BASE wallet on #TokenPocketExtension! BuildOnBase
✅In-extension #Base Tokens Cross-chain Swap.
✅Connect with third-party websites in a snap.
✅Smoothly operation and New Interface experience.
👇Add #TokenPocketExtension to your Chrome
https://chrome.google.com/webstore/detail/tokenpocket/mfgccjchihfkkindfppnaooecgfneiii?hl=en
#onchainsummer#OnChain#BASE
【Details】https://twitter.com/TokenPocket_TP/status/1691758198003532191
【Powered By】Crypto Box
🎉 Milestone Alert! 🎉
SingSing has officially surpassed 1.2 MILLION on-chain transactions! 🚀
Thank you to our incredible community for making this possible. Here’s to many more milestones ahead! 💪✨
Read more and open treasure at: X Post
#SingSing#Blockchain#Milestone#OnChain#CryptoCommunity