Установить свойства виджета в 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
🚨 Sneak Peek Alert about $SING token🚨
Big changes are coming to Tycoon Game! 🎤✨
Soon, withdrawal fees will no longer be paid in TON. Instead, we’re switching to $SING! 💎
👉 Start stacking your $SING now to stay ahead! 🔑
Tips: If you have not got $SING, easily buy at:
- BingX: https://bingx.com/en/spot/SINGUSDT/
- CoinEx: https://www.coinex.com/en/exchange/sing-usdt
#SingSing#TycoonGame#GameFi#Web3
🔧Tycoon Game Maintenance Notice🔧
Tycoon Game will be temporarily closed for maintenance starting at 7:00 AM UTC. We'll keep you updated on the reopening time.
After this maintenance, SING will be integrated into the game as announced: https://t.me/singsingchannel/1050
Thank you for your patience and support! 🌟
#GameFi#TycoonGame#Maintenance
🚀 How to Play SingSing Tycoon: Step-by-Step Guide 🚀
1️⃣ Buy $KARA: Upgrade buildings and cashiers to boost Cash income! 🔝
2️⃣ Complete Missions: Invite friends for $KARA, RUBY, and potential Cash Back in TON. 💵
3️⃣ Purchase Lucky & Kara Boxes: Get KTV NFTs or $KARA. Daily sales on SingSing’s MarketPlace! 🛍
4️⃣ Unbox Items: Go to 'KTV Game', enter 'Vault', and claim your NFTs and $KARA.
5️⃣ Unlock Floors: Use KTV NFTs to create more karaoke rooms for increased Cash income. 💸
6️⃣ Equip Karaoke Box NFTs: Boost Cash income in karaoke rooms! 💰
7️⃣ Spend $KARA and Cash: Use for features like Lucky Spin and NFT Marketplace coming soon! 🎯
8️⃣ Join Club Competition: Earn Airdrop Vouchers convertible to $SING after TGE! 🌟
#SingSing#TycoonGame#PlayToAirdrop
🚨 3 hours to go until Lucky Box Session 2 sale!
💰 Price:
✅ 150 Boxes for All: 800 RUBY each
✅ 50 Boxes for Pioneer NFT Holders: 400 RUBY each
🗓 Sale Time: 13:00 UTC, Sep 10
You'll soon be able to claim your NFT because SingSing Tycoon game is launching very soon! 🎉Get ready to dive into the karaoke empire! 🎤
#SingSing#LuckyBox#NFTs#TycoonGame
🎤SingSingers, good news!🎤
The TON withdrawal feature in SingSing is now re-enabled! Withdraw your TON and enjoy the smooth gaming experience. 💼💎
Get ready for more epic adventures in the Tycoon Game!
#SingSing#TON#GameWithdrawals#TycoonGame
🎤Announcement | Chat | X (Twitter) | Website | Game
🎤 How to Leverage Your NFTs in Tycoon Game 🎤
💥 Right now, you can equip both types of NFTs to boost your earnings! Dive into below:
1️⃣ Karaoke Box NFT
🔧 Boost earning speed in karaoke rooms from 1.5x to 8x (depending on rarity).
Common ➡️ x1.5 earning speed
Uncommon ➡️ x2 earning speed
Rare ➡️ x4 earning speed
Epic ➡️ x6 earning speed
Legendary ➡️ x8 earning speed
How to equip:
- Tap the only 'Equip' button and select your Karaoke Box NFT.
- After equipping, the NFT ID will appear as the room number.
- To unequip, tap the 'Equip' button again, press '-' button to unequip NFT
2️⃣ KTV NFT
🔧 Unlock 1-15 new floors, adding more rooms and boosting your earnings!
Common ➡️ +1 floor
Uncommon ➡️ +3 floors
Rare ➡️ +5 floors
Epic ➡️ +10 floors
Legendary ➡️ +15 floors
How to equip:
- Tap 'New Floor,' select your KTV NFT, and you're all set!
- New floors will unlock, with the NFT image displayed above the highest floor.
- To unequip, tap the KTV NFT image and press 'Unequip'.
#NFT#KTV#SingSing#Tycoongame
🎉KARA Launchpool has officially ended!🎉
Congrats to all stakers for earning huge rewards from the 1,000,000 KARA pool!
🏆 It’s time to redeem your rewards now:
D
1️⃣ Tap Detail Pool2️⃣ Hit the Redeem button 3️⃣ Confirm the transaction in Metamask4️⃣ Check your KARA balance in Tycoon Game and keep using $SING to join the AURA Launchpool!
🚀 The journey doesn’t stop here. Let’s keep thriving!
If you want more $SING, easily buy at:
- BingX: https://bingx.com/en/spot/SINGUSDT/
- CoinEx: https://www.coinex.com/en/exchange/sing-usdt
- SingSing Mini App: https://t.me/SingSing_TG_bot/app?startapp=_wallet(guideline)
#KARA#Launchpool#TycoonGame#Web3Gaming
🎉 Why Own a Tycoon Lucky Box? 🎉
1️⃣ The Tycoon Box is your chance to get early NFTs at a cheap price, purchasable with free RUBY you’ve mined 💎
2️⃣ Claim your NFTs right after the SingSing Tycoon game launch 🚀
3️⃣ These NFTs will be key to boosting your income fast in the new game 💰
4️⃣ Trade your NFTs freely on our Marketplace 📈
Note 🤫: We are still selling session 2 with less than the last 100 Boxes left, grab them now🎁
#SingSing#LuckyBox#NFT#RUBY#Tycoongame