Установить свойства виджета в 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
🗣#Earn Rewards in the Sahara Testnet
Sahara is backed by top funds with a $43M investment.
What to do:
✔️ Go to here and connect wallet
✔️ Claim free test tokens
✔️ Choose an avatar & complete tasks
✔️ React to "Legend" in community-bible on Discord
✔️ Finish Galxe quests
🟠 Guaranteed rewards via Shards
🟠 Deadline: TBA
🟠 No costs – free to join!
Big-name investors, so this one is worth grinding!
☝️ Start trading on Bybit
Crypto Drop Club 👉 SUBSCRIBE
📢Excited to partner with the Hong Kong Blockchain Association (HKBA) to drive innovation in the #Web3 space! 🤝
CyberCharge, the Web3 & DePIN charging solution that lets you #earn while you power up💰!
🚀@HKBAclub is a key player in Hong Kong’s blockchain scene.Exciting things ahead! ⚡
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
The Ultimate Bombie Strategy!💣
🔥Ready to DOMINATE the #Earn$Bombie mission and grab those TON rewards like never before?
If you’re serious about leveling up fast and stacking those $Bombie coins 🪙, follow the ultimate strategy guide to crush the competition and max out your rewards! 💥
🔫1. PRIORITIZE HIGH-DAMAGE BUILDS
Upgrade your gear smart! Here’s how you become an unstoppable force on the battlefield:
• Critical Hit Bonuses: Always focus on weapons with critical damage potential. Speed and agility are your key to victory.
• Stay Agile: Keep moving, dodge often, and strike fast. Speed kills!
🏆2. MASTER THE ARENA LIKE A CHAMPION
The Arena is where champions are made — don’t just fight hard, fight smart:
• Target Weaker Enemies: Start by targeting lower-level opponents to secure easy wins.
• Revenge Mode: Use the bottom-left corner to find enemies who beat you and strike back for revenge!
🎁3. AIRDROP BOX MASTERY — YOUR KEY TO SUCCESS
Here’s how you maximize your loot from AirDrop boxes:
• Open More Boxes: Always be on the lookout for more AirDrop boxes to score rare items.
• Boost Your Level: Increasing your AirDrop level unlocks better, rarer items — get those boosters!
⚙️4. OPTIMIZE YOUR AIRDROP SETTINGS
Don’t waste time with manual box openings — automate your success:
• Activate Auto-Opening: Enable automatic box openings in settings to save time and maximize efficiency.
• Multiple Box Openings: Based on your level, open several boxes at once. I’m currently opening 3 boxes simultaneously!
⭐️5. GO VIP FOR THE EDGE
VIP status is a game-changer if you want to stay ahead of the competition:
• Faster Rewards: Unlock and open AirDrop boxes quicker with VIP, plus get extra perks for your investment.
• More Loot, Less Time: Speed up your gameplay and get more rewards without the grind.
🪙6. MAXIMIZE WITH THE CATIZEN AIRDROP PASS
Once you hit Level 60, the game shifts to a whole new level of rewards:
• Buy 50 Stars Daily: With the Catizen AirDrop Pass, buy 50 stars daily, unlocking a box with 300 XP.
• Level 60 Bonus: At Level 60, the last box repeats daily, earning you steady rewards —between 1500 and 12,000 Bombies every day!
✋7. INVITE FRIENDS FOR EXTRA BONUSES
Teamwork makes the dream work!
• Extra $Bombie & Boxes: Every time you invite a friend, you both earn extra $Bombie and bonus boxes.
• More Friends = More Rewards: The more friends you invite, the bigger your Bombie empire grows!
💰8. SMART INVESTMENTS = BIG REWARDS
Want to level up faster? Investing wisely gives you an edge!
• Invest What You Can: Only spend what you can afford, but investing in the game can fast-track your progress.
• Unlock Better Gear: With small investments, you can unlock stronger items and rewards faster!
Let's try to reach the top as fast as possible with the guide and get huge #airdrop!
Kill Zombies, Earn $Bombie!🪙
KEEP YOUR INVESTMENT COMING TEAM
SEND YOUR DETAILS:
NAME
EMAIL ADDRESS
COUNTRY OF RESIDENCE
BTC OR USDT WALLET ADDRESS FOR RECEIVING RETURNS
#INVEST AND #EARN💰💶💶💶
KEEP YOUR INVESTMENT COMING TEAM
SEND YOUR DETAILS:
NAME
EMAIL ADDRESS
COUNTRY OF RESIDENCE
BTC OR USDT WALLET ADDRESS FOR RECEIVING RETURNS
#INVEST AND #EARN💰💶💶💶
Hello Team
Today we will focus on investment. Send your details to admin and get your investment capital ready.
Here is the best place to invest
Only serious investors needed
#Invest and #earn
💰💰💰💰💰💰💰💰💰💰💰💰💰💰💰💰
KEEP YOUR INVESTMENT COMING TEAM
SEND YOUR DETAILS:
NAME
EMAIL ADDRESS
COUNTRY OF RESIDENCE
BTC OR USDT WALLET ADDRESS FOR RECEIVING RETURNS
#INVEST AND #EARN💰💶💶💶
KEEP YOUR INVESTMENT COMING TEAM
SEND YOUR DETAILS:
NAME
EMAIL ADDRESS
COUNTRY OF RESIDENCE
BTC OR USDT WALLET ADDRESS FOR RECEIVING RETURNS
#INVEST AND #EARN💰💶💶💶
KEEP YOUR INVESTMENT COMING TEAM
Give me your details to process your registration in our Automated trading system Bot
Name
Country
Resident
Email and receiving wallet address for your profits
#INVEST AND #EARN💵💵
KEEP YOUR INVESTMENT COMING TEAM
SEND YOUR DETAILS:
NAME
EMAIL ADDRESS
COUNTRY OF RESIDENCE
BTC OR USDT WALLET ADDRESS FOR RECEIVING RETURNS
#INVEST AND #EARN💰💶💶💶
Hello Team
Today we will focus on investment. Send your details to admin and get your investment capital ready.
Here is the best place to invest
Only serious investors needed
#Invest and #earn
💰💰💰💰💰💰💰💰💰💰💰💰💰💰💰💰
ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ
Thank You For Your Wonderful Feedback And Congratulations On Your Profit Withdrawal
#INVEST#EARN