Установить свойства виджета в 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
😈The game has been brought to ROolZ!
🔥The gameplay is an unusual #clicker, where you gain experience points while you fight against the same person, who echoes whom and who has a more powerful NFT.
💎 Points for #GODL quests will be equal to $GODL token at launch.
✅ Go to @ROoLZQuest_bot
✅ Connect a TON-wallet
✅ Complete all tasks
✅ If you have ROoLZ NFT — stake them and get 6 points daily for each #NFT
😈Let's fight against each other!
⚡️Boost | 🌐Twitter
🐹Hamster Kombat:New Games Added!
Three new games have been added to Hamster Kombat:
1. My Clone Army
2. Chain Cube 2048
3. Train Miner
Play these games to earn more keys and enhance your experience!
👉https://t.me/hamster_kombat
📣 Stay updated! Subscribe to our channel
⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
#hamster#hamsterkombat#clicker#game#key#chiper#code#taptap
🌟Subscribe to stay ahead! 👈
Looking for daily answers, combos, and the latest news for the top Telegram games? You’ve come to the right place!
Every day, we bring you:
• 📌Task answers
• 💥 Combo of the Day and
top strategies
• 🌐 News and updates
Don’t miss out on any crucial information – stay updated and maximize your game experience!
🔔Subscribe👈👈
—————————————————
#games#clicker#combo#key
#cryptogames#taptap#crypto
🐹Hamster Kombat:New Card Alert!
Strong paws to move through life is now available in the Specials section, under New Cards!
👉Join Hamster Kombat
📣Stay tuned! Subscribe!
⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
#hamster#hamsterkombat#clicker#game#newcards#code#taptap
🤑NOT $0.0228 🚀
Notcoin has already brought in tens of thousands of dollars. The next projects that will bring in no less profit than NOT are Blum, HOT Near Protocol. All the other projects we are working on are also good.
🪙Top 24 projects
👉🥇Blum
🪙
👉🥈HOT NEAR Wallet
🪙
👉🥉PixelTap!🆕
🪙
👉4. Bull Run
👉5. Pocket Rocket
👉6. Empires Battle
👉7. PocketFi🆕
👉8. Cexio
👉9. Cyber Finance
👉10. IcebergAppBot
👉11. MemeFi
👉12. Catizen Mntbot
👉13. Catizen
👉14. Hamster Kombat
👉15. TapSwap
👉16. Dotcoin
👉17. Vertus
👉18. FirstFisher.
👉19. W-Coin
👉20. CEDEXTap
👉21. DRUM🥁
🥁
👉22. TimeFarm
👉23. Cubes = Join our pool🆕👈
👉24. Cityholder🆕
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
🔥Claim/288 activationsFiredrop0.15 HOT
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
⌨️Expected total profit from all projects: $150,000.
#Pixelverse#crypto#btc#ton#taptap#clicker#game#cexio#blum#hot
🌟 WELCOME TO GUMART 🌟
🛒 Shop till you drop with our AI-powered Telegram bot! 🚀
💰 Secure, Fun, and Rewarding - the future of shopping is here! 🛒
🎁 Exclusive rewards await! Join the Gumart mall now and get in on the action! 🛍
Hint: Early Gumarters will gain a significant advantage 😉
#ecommerce#shopping#taptap#clicker#game#p2e
🤑NOT $0.02418🚀
Notcoin has already brought in tens of thousands of dollars. The next projects that will bring in no less profit than NOT are Blum, HOT Near Protocol. All the other projects we are working on are also good.
🪙Top 24 projects
👉🥇Blum
🪙
👉🥈HOT NEAR Wallet
🪙
👉🥉PixelTap!🆕
🪙
👉4. Bull Run
👉5. Pocket Rocket
👉6. Empires Battle
👉7. PocketFi🆕
👉8. Cexio
👉9. Cyber Finance
👉10. IcebergAppBot
👉11. MemeFi
👉12. Catizen Mntbot
👉13. Catizen
👉14. Hamster Kombat
👉15. TapSwap
👉16. Dotcoin
👉17. Vertus
👉18. FirstFisher.
👉19. W-Coin
👉20. CEDEXTap
👉21. DRUM🥁
🥁
👉22. TimeFarm
👉23. Cubes = Join our pool🆕👈
👉24. Cityholder🆕
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
🔥Claim/288 activationsFiredrop0.15 HOT
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
⌨️Expected total profit from all projects: $150,000.
#Pixelverse#crypto#btc#ton#taptap#clicker#game#cexio#blum#hot#durov
💎 The $6 million worth of Notcoin donated to me 2 weeks ago has increased in price 4 times and is now valued at $24 million 📈
🚀 The daily trading volume of Notcoin reached $4 billion yesterday, making it one of the top 5 most-traded cryptocurrencies in the world 🏅
🪙 Millions of people earned money on Notcoin just by using a mini app in Telegram — and now they keep earning more. While the Notcoin mini app is accessed via Telegram, the Notcoin cryptocurrency is minted on TON — the only blockchain technology that is truly scalable and can support a new wave of super popular projects 🔋
💪 A month ago, Notcoin was the largest cryptocurrency community in the history of social media. Today, the Notcoin community is rivaled only by projects it inspired — similar mini apps on Telegram that are allowing tens of millions of users to benefit 🫰
🫡 We are proud to be the platform that serves the people.
❤️Source https://t.me/durov
🤑NOT $0.02418🚀
Notcoin has already brought in tens of thousands of dollars. The next projects that will bring in no less profit than NOT are Blum, HOT Near Protocol. All the other projects we are working on are also good.
🪙Top 24 projects
👉🥇Blum
🪙
👉🥈HOT NEAR Wallet
🪙
👉🥉PixelTap!🆕
🪙
👉4. Bull Run
👉5. Pocket Rocket
👉6. Empires Battle
👉7. PocketFi🆕
👉8. Cexio
👉9. Cyber Finance
👉10. IcebergAppBot
👉11. MemeFi
👉12. Catizen Mntbot
👉13. Catizen
👉14. Hamster Kombat
👉15. TapSwap
👉16. Dotcoin
👉17. Vertus
👉18. FirstFisher.
👉19. W-Coin
👉20. CEDEXTap
👉21. DRUM🥁
🥁
👉22. TimeFarm
👉23. Cubes = Join our pool🆕👈
👉24. Cityholder🆕
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
🔥Claim/288 activationsFiredrop0.15 HOT
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
⌨️Expected total profit from all projects: $150,000.
#Pixelverse#crypto#btc#ton#taptap#clicker#game#cexio#blum#hot#durov
💸$110,000 GIVEAWAY THIS WEEK💸
🔥Pixelverse is dominating! We've reached 5 million users and 1 million daily active members!
A massive THANK YOU to our incredible community for your support. To celebrate, we’re launching a $110K Prize Pool! 💥
https://t.me/pixelversexyzbot?start=5888609969
Here's how the prizes will be distributed:
🔥$50K Raffle:
👍 Invite 2+ people this week (3 - 9 june) and get 1 raffle ticket.
🏆 300 winners will be randomly chosen.
🔥$60K based on Weekly Referral Leaderboard:
🥇 1st place: $10,000
🥈 2nd place: $6,000
🥉 3rd place: $3,000
🏅 4th-10th places: $1,000 each
🎖 11th-20th places: $500 each
🏆 21st-50th places: $300 each
🏅 51st-100th places: $200 each
🏅 101st-300th places: $50 each
ℹ️ Don't forget to enter your wallet address in #PixelTap in the wallet section (will be available starting today) to qualify for your prizes.
Let's make history and smash our goals together! 💪🔥
#Pixelverse#crypto#btc#ton#taptap#clicker#game#p2e#promox
t.me/pixelversexyzb👈
°