Установить свойства виджета в 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
🎁 Share $150,000 in ZETA!
Join UltiverseDAO with TokenPocket_TP, one of the events on #TokenPocketChristmas!
👉https://galxe.com/TokenPocket/campaign/GChG6ttcDb
✅Finish the on-chain task with ZERO cost on zetablockchain Testnet, follow the guide, and claim your Testnet token.
👉https://tp-lab.tptool.pro/tokenpocket-christmas/?locale=en#/
✅Ultiverse Tutorial UltiverseDAO
👉https://ultiversedao.medium.com/tokenpocket-christmas-with-ultiverse-and-zetachain-meta-merge-match-three-tutorials-79a67fe45843
【Details】https://twitter.com/TokenPocket_TP/status/1743563318995099984
【Powered By】Crypto Box
🎁 Share $150,000 in ZETA!
Join zkme_ Journey with TokenPocket_TP, one of the events on #TokenPocketChristmas!
👉https://galxe.com/TokenPocket/campaign/GCnW8tthSy
✅Finish the on-chain task with ZERO cost on zetablockchain
Testnet, follow the guide, and claim your Testnet token.
👉https://tp-lab.tptool.pro/tokenpocket-christmas/?locale=en#/
✅zkme_ Tutorial
👉https://medium.com/@zkMe/spread-holiday-cheer-with-zkme-identity-oracles-your-christmas-lucky-sign-06c69eaa3fd3
🎁 Share $150,000 in ZETA!
Join zetaswapdex Journey with TokenPocket_TP, one of the events on #TokenPocketChristmas!
👉https://galxe.com/TokenPocket/campaign/GCTy6ttCqT
✅Finish the on-chain task with ZERO cost on zetablockchain Testnet, follow the guide, and claim your Testnet token.
👉https://tp-lab.tptool.pro/tokenpocket-christmas/?locale=en#/
✅Tutorial
👉https://medium.com/@zetaswapdex/zetaswap-and-tokenpocket-christmas-campaign-tutorial-4da9812bc3cd
【Details】https://twitter.com/TokenPocket_TP/status/1740366182635692379
【Powered By】Crypto Box
Quoted ChatGM_Official : ❄️JOIN https://galxe.com/TokenPocket/campaign/GCgP6tt9zy on Galxe and get to chance to share $150,000 in ZETA #TokenPocketChristmas Gift!
👉https://tp-lab.tptool.pro/tokenpocket-christmas/?locale=en#/
👉https://www.tokenpocket.pro/
【Details】https://twitter.com/TokenPocket_TP/status/1739132332236566541
【Powered By】Crypto Box
#TokenPocketChristmas $9,000 Random Rewards on Owlto_Finance!
✅ Bridge between any network on https://owlto.finance/bridge?channel=2484
✅ Connect with your TokenPocket Wallet on Owlto
✅ Follow Owlto_Finance and TokenPocket_TP
✅ Q'RT this tweet with #TokenPocketChristmas.
⏰ Dec 20th - Dec 26th, 2023
💎 Bridge and get a chance to win up to $100 per day at once!
【Details】https://twitter.com/TokenPocket_TP/status/1737681781900578863
【Powered By】Crypto Box
🧑🎄Merry Christmas! #TPFam#TokenPocketChristmas
❄️May your wallets be filled with joy, your transactions be seamless, and may the blockchain of happiness bless you with endless prosperity.
Wishing you a Merry Christmas and a crypto-filled New Year! 🚀🌟
👉https://www.tokenpocket.pro/
【Details】https://twitter.com/TokenPocket_TP/status/1738895386377601385
【Powered By】Crypto Box
#TokenPocketChristmas is listed on Galxe's Banner!
👉https://galxe.com/TokenPocket/campaign/GCc28ttYTk
🎅Welcome to join #TokenPocketChristmas and get a chance to share $150,000 in #ZETA! zetablockchain
【Details】https://twitter.com/TokenPocket_TP/status/1738034178892132511
【Powered By】Crypto Box
🎁 Share $150,000 in ZETA! zetablockchain
Join ChatGM_Official Journey with TokenPocket_TP, one of the events on #TokenPocketChristmas!
👉https://galxe.com/TokenPocket/campaign/GCgP6tt9zy
👉https://tp-lab.tptool.pro/tokenpocket-christmas/?locale=en#/
ChatGM uses Interactive AI to make web3 simple and accessible to everyone. With EVM/BTC wallets as digital IDs, ChatGM offers encrypted texting, voice, and video calls across crypto wallets, Telegram, and WhatsApp.
🌊Tips, #ChatGM OAT is representing the POAP of ChatGM OG, make sure you already minted the OAT. Converting POAP into GM Points enables users to exchange these points for GM tokens during future airdrop events, based on the pool's conversion rate.
【Details】https://twitter.com/TokenPocket_TP/status/1745747011113300328
【Powered By】Crypto Box
🆕 Galxe now fully supports #TokenPocket login!
👉https://extension.tokenpocket.pro/
Galxe is the leading platform for building the Web3 community.
🔥Follow TokenPocket Space and Get Ready for the #TokenPocketChristmas on #Galxe!
👉https://galxe.com/TokenPocket
Details:
👉https://twitter.com/Galxe/status/1729918366012600584
👉https://twitter.com/TokenPocket_TP/status/1730068829311774726
💥We’re excited to announce that #TokenPocketChristmas winners can claim rewards at
@ZetaBlockchain
mainnet launch! #ZetaChain
Check if you are on the first-round winner list
👉https://docs.google.com/spreadsheets/d/1zqZx0BHE0gVBn8doFhRAdFBaQrwoxzPbwu2CYCOkvhs/edit#gid=0
How to claim your #ZETA?
1️⃣Download TokenPocket Wallet
👉https://tokenpocket.pro
👉https://extension.tokenpocket.pro
2️⃣Create/import/sync your #ZetaChain wallet on TokenPocket after mainnet launch!
3️⃣Share the news with your friends if you are on the winner list! (RT, Like, Comment) 👉https://twitter.com/TokenPocket_TP/status/1752147092942749951
When to get your ZETA?
⏰The rewards will be distributed at the same time of #ZetaChain airdrop claim opens this week.
All participating user data from #TokenPocket are also whitelisted to get a boost in the first XP campaign on ZetaHub. Learn more about the 10% of the total ZETA token supply for community rewards: https://twitter.com/zetablockchain/status/1750758520637804707
#TokenPocketChristmas ZoomManor #Giveaway!
🫶To Enter👇
https://galxe.com/TokenPocket/campaign/GCDC5ttVi6
🧙♂️ZoomManor is a farm management🐣🌾and home-building game built on #X1▪️and multi-chains in the future🏡 ZoomManor
🪂50 winners will share 500 USDT and 20 winners will share 20 Hero Mystery Boxes!
【Details】https://twitter.com/TokenPocket_TP/status/1739547968599142506
【Powered By】Crypto Box
😍Are you hooked on #Solana? Dive into the world of high-speed transactions and decentralized greatness! 🚀 Embrace the Solana thrill!
Now, $SILLY as one of the top trending tokens on solana, is listed on TokenPocket wallet! #SillyDragon
Empowering you with real-time price updates and dynamic percentage changes! Stay informed, stay ahead. 📈✨#TokenPocketChristmas#TokenPocket
👉https://www.tokenpocket.pro/
【Details】https://twitter.com/TokenPocket_TP/status/1739203251525103701
【Powered By】Crypto Box