Установить свойства виджета в 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
Guys @MyCoralApp NFTs, which BinanceLabs is an investor and supporter of, were recently minted for free. It currently has a price of around $2-3.
Coral has a phone and those who own it earn tokens.
The project will distribute a large portion of the total supply as an airdrop! I added it to my bag in case there might be a surprise for NFT owners.
floor went from $2 to $4 and is still cheap #nfa
See the collection : https://magiceden.io/collections/bsc/0x6dfbb01ecb7991366cd8acc4d18dcc67bbe345ba
🎁21,900 $DORA Airdrop on BNBCHAIN!
→https://zealy.io/cw/tokenpocket/questboard
*Exclusively for the community. No investment advice — just memecoin fun! #NFA
All Bonk-Ending Tokens Now Tradable on TokenPocket! 🎉
Trade ANY token that ends with 'bonk' on Solana —whether pre-launch or live—all in one place with TokenPocket’s Meme Mode! 🚀
#NFA
Pump with TokenPocket!
📱http://tp.xyz
💻http://swap.transit.finance
⚪️
🪙RUDY FL PRESALE LIVE AND ENDS IN AROUND few hours
🪪
✅
✅
🪪
⭐️Based team so keep a watch for your best entries. Dyor,Nfa.
Rudy is a legendary character based on a famous animated movie! He is an animal lover and passionate about exercise and investments. Now, Rudy lives on the Solana blockchain, becoming the purple mascot of the purple chain, Solana.
➡️Join Rudy on this exciting adventure in the world of cryptocurrencies and be part of his vibrant and fun community.
✅
Ⓜ️ CMC &
🦎CG fast track
✅ Marketing team
✅
✅Safu /
✅ Audit /
🪪KYC /
🪪Doxx
✅ LP locked 1 year
😊Pinksale Buy Link❤️👤🛡🔰:
https://www.pinksale.finance/solana/launchpad/2bX7RbeMygiiLDAp5MSTsZELQh7fqHQncApeRww2788k
🌐Website
✖️Twitter
✈️Telegram
#DYOR#NFA
Calling all Degens! 🗣️
A new Bot launches today:https://Palomabot.ai🐦🤖
Palomabot runs on the Paloma blockchain and partners with major AMMs and players to create MEV bots 🚫 that can trade momentum with no sandwich and with maximum backrun proits.
First Fast-Snipe Bots launching today:
* Paloma Momentum Bot
* CoinGecko Top 100 Bot
* Coingecko Newest $1MM Marketcaps Bot
* Curve Stop Loss and TWAP Bot
🤖 All Paloma Bots Snipe in 1-second and include limit orders to maximum profits & automatically exit positions.
💰 All money is returned to your wallets when positions close.
🔐 All money is custody by the Paloma blockchain so no rug-pull.
🔔 Telegram Alerts every hour for the hottest tokens to bot and profit.
🏆 All Bots transactions qualify for Paloma GRAIN token rewards.
Come degen with us and tell us what bots you want to use next!
https://Palomabot.ai🐦🤖
#NFA#DYOR
#DYOR#NFA
SCALE 🟡 APPARENTLY WELL STABILIZED, HAS A LOT OF POTENTIAL FOR GROWTH
if you think interesting, buy some bags!
DYOR • NFA
Mc now $27k
Tg : https://t.me/meta2k22bsc
Web : under construction
Chart : https://poocoin.app/tokens/0xb4039ec127cbab1e2bbd62aabf920aa57a900ecb
Ca : 0xb4039ec127cbab1e2bbd62aabf920aa57a900ecb
Ownership Renounced, Community based, Lp lock 1 month mudra
⚛️@TeamTanukiToken
Are you sick to death of reward tokens and useless projects lead by inexperienced development teams who constantly over promise and under deliver? Don't worry, we've got something super special to share with you😘
Our project, is lead by an experienced solidity & artificial intelligence development team. Here is just a snippet of what's instore;
• Initial simple contracts (Lottery, BNB fund, etc)
• Exchange listings
• Promotional Material for Future AI Contracts
• First AI Driven Contract
• Promotional material on “AutoTainment”
• Announcements of further AI products
• Extended DApp to track AI rewards
• Major exchange listings
• Advanced AI SC's
⚛️Marketing Statement
• Our first goal is to drive organic growth by being welcoming to newcomers into our ecosystem and community
• We like to market our unique attributes, we are a dog coin, but no one has done a raccoon dog before
🟣Telegram: http://t.me/TeamTanukiToken@TeamTanukiToken
🟣Website: http://tanukitoken.finance
#DYOR#NFA
#Advertisement#NFA
📣We call to our Investors!
📌 Just one step: From purchasing NFTs to creating and co-founding the bank of the future: TLVD Trusty Bank!
Closed listing by founders from May 9, 2024!
💎 Open sale of NFTs on the DeFi marketplace OpenSea begins on June 10, 2024!
UNION IS STRENGTH!
💬Contact:+372 5837 7377
🔍More information about the project:
✈️Telegram |⛵️Opensea |🌐Website
🔴Note:Please do your own research (DYOR) before joining to any project. Nothing in this post is financial advice (NFA).
✈️Business:@ProjectPromoters✅
#Advertisement
🚀 Don't miss out on the QUBY AI PRESALE! 🎮✨
Dive into the future of gaming and be part of the next big thing at http://QUBYAI.com🔥
Unlock exclusive benefits with CODE: QUBYAI2024 🔓
💬Note - Please do your own research (DYOR) before joining any presale, Invest only that part of your portfolio which you can afford to loose #NFA.
🔥Earn Hub is Now Live!
We’re excited to announce that Uniswap & PancakeSwap LP earnings are now officially live in the Earn section!
Simply provide liquidity to top token pairs and enjoy steady, stable returns on your assets.#NFA#DYOR
📱Discover -> Earn Section
https://x.com/TokenPocket_TP/status/2046770434952339884?s=20