Установить свойства виджета в 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
Bitcoin Hits $94,000 Amid Sovereignty Claims
Bitcoin reaches $94,000. Jason Lowery states that permissionless control over property through Bitcoin equates to sovereignty.
Source: Bitcoin News
#Bitcoin#Crypto#Finance#Market#Sovereignty#BTC#Investing#Wealth#Blockchain#Assets
There's a lot to be made by tapping and claiming coins from the Go! Ton App!
Get started Here: https://t.me/thegoprojectBot
This bot is your free pass to Sweet rewards, get started Now.
Once you get started, you've got to maintain your spot as a weekly and monthly active user. Here's why:
🔹 There are more rewards as you get more active
🔹 You get features nobody else gets
🔹 You get into higher ranks which means exclusive airdrops will be sent to you.
🔹 You get access to collectibles reserved just for you
🔹 You get to Contribute more to the community, and influence the direction of the project
Ready to start Tapping?
Let's Go: https://t.me/thegoprojectBot
#gotonapp#tap2earn#bot#rewards#boost#wealth
Join: 🐣X✉️Chat✉️News🤖Discord
Play: 🕹️TON App💻Web App
Info: 🖥Newsletter🌐Website🌐Blog
Rich Dad vs Poor Dad mindset 💸
Poor Dad: “Money comes when you work.”
Rich Dad: “Money comes when you build a system.”
The lesson:
Don’t only trade time for money.
Build assets, skills, and processes that pay you repeatedly.
Today’s action:
Pick ONE system to start:
• automate savings/investing
• create a digital product
• build a side business workflow
#RichDadPoorDad#money#wealth#mindset#financialfreedom#selfimprovement#books
🚀 Analyst Price Targets: $2–$5 Long Term 🚀
Royals see it. Whales see it.
Do you?
Buy at $0.00405 before it’s too late.
👉www.shheikh.io
#Crypto#Blockchain#AI#RWA#DeFi#Tokenization#Altcoins#CryptoCommunity#Presale#BullRun2025#NextBigThing#Wealth
🔥Presale – SHHEIKH Phase 2 (LIVE) ✅
💠Total Reward: Token Raises $6.92M+ in Phase 2, Attracts Global Investors
🚨SHHEIKH Presale Surpasses $6.92M+ — Momentum Is Unstoppable 🚨
✅ $6.92M+ raised
✅ 2.21B+ tokens sold
☀️Presale Link: – Click Here
♦️AI + RWA = the next trillion-dollar blockchain market.
♦️Secure SHHEIKH at $0.00405 before the next surge.
♦️Follow their Twitter account
♦️Join their Telegram Channel
📅End Date: TBA
📤Distribution: After campaign ends
®Note - Please do your own research (DYOR) before joining to any airdrops project.
#Crypto#Blockchain#AI#RWA#DeFi#Tokenization#Altcoins#Presale#CryptoCommunity#Wealth#FutureOfFinance#BullRun2025
📦New Project Spotlight: SHHEIKH Token 🔥
🪙 Phase 2 Live: $0.00405 + 5% Bonus
💎Rating: ⭐️⭐️⭐️⭐️⭐️
🔗Participate now: www.shheikh.io
===========================
📣How to participate:
✅Visit www.shheikh.io
✅ Connect your wallet
✅ Purchase SHHEIKH tokens (Min: $10)
✅ Receive instant 5% bonus
✅ Follow their Twitter & Join Telegram
===========================
🖥SHHEIKH has raised $6.53M+ USDT and sold 2.05 BILLION tokens in Phase 2. Recognized as the #1 AI + RWA project of 2025, combining artificial intelligence with real-world asset tokenization.
🚨Why investors are watching:
✅Royals & whales accumulating positions
✅ $6.53M+ raised from global investors
✅ Analysts' top AI + RWA pick for 2025
✅ Still early entry before phase closes
#Crypto#Blockchain#AI#RWA#DeFi#Altcoins#Tokenization#BullRun2025#NextBigThing#Presale#Wealth#CryptoCommunity
🔴Note:Please do your own research (DYOR) before participating. This is not financial advice (NFA).
Sheldon Schiff Proposes USAcoin
Peter Schiff advocates replacing Bitcoin as a strategic US reserve with a new crypto asset, USAcoin, featuring a limited supply of 21 million coins and an improved blockchain for better payment capability. He highlights this shift as a pathway to wealth, contrasting his views on Bitcoin, which he refers to as digital gold. Schiff also generated an image with Elon Musk and Donald Trump against a Bitcoin backdrop, criticizing ChatGPT for its content restrictions.
_"HODL to the Moon, America!"_
#PeterSchiff#USAcoin#Crypto#Bitcoin#Blockchain#Investment#DigitalGold#Wealth#PaymentSystems#Grok
Bitcoin Surges to $102,000
Bitcoin's price has skyrocketed to $102,000, marking a significant milestone in its market value. This surge indicates rising investor confidence and increasing demand in the cryptocurrency sector.
#Bitcoin#Crypto#Market#Finance#Investing#BullMarket#Blockchain#Volatility#Trends#Wealth#Trading#Technology#Asset#DigitalCurrency#PriceRise
📦Exclusive Project Spotlight: SHHEIKH Token 👑
🛍 Phase 2 Price: $0.00405 | Minimum: $10 USDT
💎 Status: Gaining Major Royal Attention
🔗Official Site: www.shheikh.io
===========================
📣How to Participate:
✅Visit www.shheikh.io
✅ Connect Your Wallet
✅ Purchase SHHEIKH Tokens
✅ Follow Twitter & Join Telegram
===========================
🔥SHHEIKH has raised $6.53M+ USDT with confirmed interest from Middle Eastern royal investors. This AI-powered RWA project represents real institutional momentum and technological innovation.
🚨Key Highlights:
✅$6.53M+ raised from global investors
✅Middle Eastern royals in active talks
✅ Real institutional power and backing
✅ Limited time remaining in Phase 2
#Crypto#Blockchain#AI#RWA#DeFi#Altcoins#Tokenization#Presale#CryptoCommunity#BullRun2025#Wealth#NextBigThing
🔴Note:Please do your own research (DYOR) before participating. Nothing in this post is financial advice (NFA).
Massive $4M Profit in Hours!
Mr. Burns profited over $4 million within six hours of trading the VINE token. Initially investing $70k, he sold 9.96 million VINE for $2.36 million while retaining 4.67 million VINE worth $1.73 million—highlighting a surge in the token's value. 📈
Full story: Mr. Burns’ Trading Success
#Crypto#VINE#Trading#Profit#Investing#Tokens#Blockchain#ATH#Finance#Wealth#MrBurns#VentureCapital#Speculation
BlackRock Launches Bitcoin ETP in Europe
BlackRock, the largest asset manager globally, is set to launch an exchange-traded product (ETP) linked to Bitcoin in Europe. Marketing may start this month, marking BlackRock's first crypto-linked ETP outside North America. Read more
#BlackRock#Bitcoin#ETP#Crypto#Finance#Investment#Europe#Assets#Market#Trade#Blockchain#News#Regulation#ETF#DigitalAssets#Wealth#Trading#Economy#Global#FinanceNews
Mirabelle Secures $1.05M Funding
Mirabelle, specializing in mortgage life financing for seniors, has secured $1.05 million in funding as of December 3, 2024. The service aims to enhance retirement experiences by valuing wealth while allowing seniors to remain in their homes.
#Funding#Mortgage#LifeFinance#Seniors#Retirement#Housing#Wealth#FinancialServices#Mirabelle#Finance