Установить свойства виджета в 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
🔥「0」Gas $U Transfers on BNBCHAIN with TokenPocket!
TokenPocket now enables transferring $U with 0 gas fee on the BNB Chain automatically - enjoy smooth, 0-gas transfers, all with a secure, wallet-native experience.
Your first choice of #StablecoinWallet
👉http://tp.xyz
https://x.com/TokenPocket_TP/status/2003755846489231701?s=20
🆕$U is now listed on TokenPocket!
Manage your $U seamlessly with TokenPocket_TP: store, send, and swap in one powerful multi-chain #StablecoinWallet.
Track Easier! Trade Smarter!
👉http://tp.xyz
🟦 TokenPocket Weekly Report 🟦
🔵 Supported $U on TokenPocket.
🔵 Embrace New Era of #StablecoinWallet
🔵 Notice of Wallet Service Upgrade
🔵 Listed 5 DApps.
All-in-one, all in TokenPocket 👉http://tp.xyz
🚀TokenPocket Now Supports Multi-Chain Gas Payment with Stablecoins!
Powered by EIP-7702, TokenPocket now enables transferring gas payments in $USDT, $USDC, and more across multi-chains — including BNBCHAIN, base, and arbitrum — for a smoother, more cost-efficient transfer experience.
🔥 Explore it now in #StablecoinWallet!
🔗Tutorial
🧊Be Your First #StablecoinWallet!
→ https://help.tokenpocket.pro/en/wallet-operation/stablecoin/wallet
✅ Self-custody, your keys, your coins!
✅ Multichain supported — one wallet, all chains!
✅ Gas-free stablecoin transfers on BNBChain & Tron (more coming!)
🔐 Powered by TokenPocket — simple, secure, seamless.
📝 TokenPocket Monthly Report — June 2025
📖 Read the full report: https://tokenpocket-gm.medium.com/tokenpocket-monthly-report-june-2025-8a642e365b94
Main Upgrade ⏬
🎯#StablecoinWallet
🎯 Market Chart Upgraded
🎯 Gas-Free Transfer on TRON and BNBChain
🎯 Security Enhancement: Now supporting native MultiSig wallets for Bitcoin and Core — giving your assets even stronger protection.
✍️Share your thoughts and suggestions through our survey for a chance to win exclusive prizes. Every piece of feedback is valued!
✍️ Fill out the Q&A⏬
https://docs.google.com/forms/d/e/1FAIpQLSe8tElYK6V6qN5MqDtDIj7G7SjUw3cSv3bwC-rSXyLVq2USRQ/viewform?usp=send_form
📍 All In One, All In TokenPocket!
🔗https://tp.xyz
🔥USDT Supply on the TRON Surpasses $80 Billion, now accounting for over 51.74% of global circulation, making TRON the leading stablecoin network.
TokenPocket plays a key role by helping users save on gas through innovations like USDT gas payments, one-click energy rentals, and daily subsidy programs.
In 2025, TokenPocket continues to scale stablecoin usability — reinforcing its position as the go-to #StablecoinWallet for global users!
https://x.com/TokenPocket_TP/status/1936994956620750933
🎁 Pay Gas with Stablecoins & Share a Price Pool of $2,000
→https://zealy.io/cw/tokenpocket/questboard/sprints
🚀 New round of #StablecoinWallet Campaign is now live on zealy — complete quests and experience paying gas fees with stablecoins via TokenPocket.
*Exclusively for the community. No investment advice! Any new quests will be announced in our Telegram community first.💕💕#NFA
📝 TokenPocket Monthly Report — January 2026
In January, TokenPocket focused on stablecoins, security enhancement and trading experience.
🎯#SAFU
TokenPocket now supports Solana Multi-Sig Wallet with native integration. Multi-Sig, Multi- Safe.
🎯 Advanced Trading Experience
TokenPocket has expanded Limit Order support to
Ethereum, Base, BNB Chain, Arbitrum, and Polygon. With limit orders, users can define their target prices in advance and execute with more discipline. Better execution quality with less time spent watching charts.
🎯#StablecoinWallet
TokenPocket now supports stablecoin gas payment on
Base, BNB Chain, Polygon, Arbitrum, and Ethereum, and this capability is also available in Swap & Bridge. That means users can pay network fees with stablecoins in more scenarios, reducing reliance on native gas tokens and making transfers, swaps, and bridging much smoother.
📍 All In One, All in TokenPocket
https://tokenpocket-gm.medium.com/tokenpocket-monthly-report-january-2026-2c48e070338e
🚀 Keep Enjoying BNBCHAIN Gas-Free Stablecoin Transfers with TokenPocket!
✅ Supports $USDC & #USD1 - Ends on Nov 30, 2025.
( $USDT Support Ended on Oct 31, 2025)
🔷 Perfect for daily transfers with user-friendly interface.
Unlock the future of #StablecoinWallet with TokenPocket.
👉http://tp.xyz
🎉 Enjoy Gas-Free Stablecoin Transfers on BNBCHAIN with TokenPocket.
✅Supports $USDT & #USD1 - Ended on July 31
🔷Perfect for new users & everyday transfers.
Transfer smarter with your #StablecoinWallet!
👉https://tp.xyz