Установить свойства виджета в 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
New issue of Uzbekistan Central Securities Depository’s monthly newsletter “depo-REPORTER” covering key depository news of September 2022.
Download depo-REPORTER No 13 (PDF, 0.8 Mb)
#depo#reporter#news#central#depository#securities#issues
deponet.uz|Tg|Fb|Inst|Youtube
New issue of Uzbekistan Central Securities Depository’s monthly newsletter “depo-REPORTER” covering key depository news of August 2022.
Download depo-REPORTER No 12 (PDF, 0.8 Mb)
#depo#reporter#news#central#depository#securities#issues
www.deponet.uz|Tg|Fb|Inst|Youtube
BitMEX Seeks Buyer with Investment Bank Help
BitMEX, a prominent cryptocurrency exchange, is actively looking for a buyer and has engaged Broadhaven Capital Partners for assistance. Founded in 2014 by Arthur Hayes, BitMEX faced legal challenges in the U.S. concerning anti-money laundering protocols, leading to Hayes' resignation as CEO. For more details, read here.
#BitMEX#Crypto#VC#Blockchain#Exchange#Investment#FinTech#AML#Securities#Trading#Cryptocurrency
U.S. Releases Seized Crypto Mining Machines
U.S. authorities begin releasing seized Chinese-made cryptocurrency mining machines, totaling up to 10,000 units at various ports. Synteq Digital's CEO notes resistance from some CBP officials towards Bitcoin mining, hindering the industry's growth.
🔗Read more
In related news, BioNexus Gene Lab approves Ethereum as its treasury asset; Bitcoin open interest reaches lowest since August; and Bitwise files for Aptos ETF.
🔗BioNexus News
🔗Bitcoin Open Interest
🔗Bitwise Filing
#Crypto#Bitcoin#Ethereum#Mining#BioNexus#Aptos#ETF#VC#Blockchain#Finance#Investment#DeFi#Securities#Regulation#Innovation#MarketTrends#OpenInterest#USeconomy
Milei Withdraws LIBRA Support Amid Cash Out
Argentinian President Javier Milei retracts his endorsement of $LIBRA after insiders reportedly cashed out $107 million. The move raises questions about transparency and the impact on the cryptocurrency's reputation. For more details, visit The Block.
#Argentina#Milei#LIBRA#Crypto#DeFi#Blockchain#Investment#Transparency#Finance#Market#News#Updates#Economy#InsiderTrading#Regulation#Securities#Volatility#Trends#DigitalCurrency#Cryptocurrency
Major Updates on Bitcoin and Ethereum
🔗 *Roman Storm secures legal funding for trial* with support from Paradigm and Vitalik Buterin! Details here: Leviathan News.
🔗 David Sacks confirmed evaluating a *national Bitcoin reserve* is a priority for Trump's Digital Assets Task Force. BTC is touted a *superior store of value*. Regulations on crypto incoming within six months!
🔗 XRP Ledger briefly halted due to validation issues but self-healed. More info: Coindesk.
🔗 Hong Kong weighs *Bitcoin as a strategic reserve*, urging to accelerate feasibility studies. Insights here: Wu Blockchain News.
🔗 Ethereum's *supply rises* back to pre-merge levels due to Dencun upgrade, signaling inflation. More: The Block.
🔗 U.S. to consider Bitcoin reserve as an essential economic security asset; institutional adoption underway!
#Bitcoin#BTC#Ethereum#ETH#Crypto#Legal#Funding#XRP#Regulations#HongKong#StrategicReserve#DigitalAssets#AI#VC#MicroStrategy#Inflation#Securities#DeFi#Stocks#Bonds#ETFs
Tokenized Mining Notes Coming to El Salvador
Bitfinex Securities to launch Blockstream Mining Note 2 (BMN2) in Q1 2025. BMN2 offers returns based on bitcoin mined by Blockstream. Previous note (BMN1) delivered over 1,212 BTC to investors in three years. More details in the article here: Read more
#Bitfinex#Blockstream#BMN2#ElSalvador#Bitcoin#Crypto#Investment#Tokenization#Mining#BTC#Finance#DeFi#DigitalAssets#Securities#Blockchain#Trading#Market#Returns#BMN1#Innovation#Economy
Metaplanet Plans $745M Bitcoin Purchase
Tokyo-listed Metaplanet aims to raise ¥116 billion (approx. $745M) through 21 million share subscriptions at 0% discount for Bitcoin acquisitions. This represents one of the largest financing plans for Bitcoin by any Asian publicly traded company. Detailed info available here: link. Meanwhile, U.S. Bitcoin and Ethereum ETFs received $1.9B in inflows during Trump's first week, bringing total digital asset inflows for 2025 to $4.8B. U.S. Senate also confirmed pro-crypto Scott Bessent as Treasury Secretary, expected to influence crypto regulations amid heightened interest.
#Bitcoin#ETF#Crypto#Investment#Metaplanet#Asia#Treasury#DigitalAssets#BTC#ETH#Finance#NASDAQ#WallStreet#MarketTrends#Inflows#Securities#Cryptocurrency#USeconomy#Regulations#Trump#ProCrypto
Argentina's Opposition Eyes Impeachment Over LIBRA
Argentina's opposition is considering impeachment for President Milei after conflicting support for the LIBRA token. This follows a controversial launch that saw rapid investment and then a significant drop in value, leading to accusations of mismanagement and deception. The situation raises questions about political influence in cryptocurrency projects.
Read more: Reuters
#Argentina#LIBRA#Crypto#Impeachment#Milei#Investment#MarketManipulation#EconomicCrisis#Blockchain#DeFi#RugPull#Politics#Cryptocurrency#TokenLaunch#InsiderTrading#Securities#AI#VC
Thai SEC Considers Bitcoin ETF Approval
The Thai Securities and Exchange Commission is evaluating a proposal to approve a Bitcoin ETF for listing on its local exchange. Currently, Thai investors can only access overseas Bitcoin ETFs through a fund of funds product launched in mid-2024. Read more
#Thailand#Bitcoin#ETF#Crypto#Investing#Finance#USDC#fxUSD#XRP#WhaleAlert#Assets#Trading#Decentralized#Yield#Securities#Exchange#LocalMarket#DigitalAssets#BlueChip#Stablecoin#VC
Trump Establishes Strategic Bitcoin Reserve
Former President Trump has signed an order to create a strategic Bitcoin reserve in the U.S., based on approximately 200,000 BTC confiscated by the government. This reserve will serve as a savings asset, not intended for sale, acting as a digital Fort Knox. Meanwhile, analysts indicate that governments may follow the U.S. lead, reducing the likelihood of Bitcoin bans from regulators. Post-announcement, Bitcoin saw a price drop from $91,000 to $85,000 but has since recovered to $88,000. No altcoins are currently included in the reserve plans. Full details here: Reuters
#Bitcoin#crypto#Trumpr#US#Blockchain#Finance#Regulation#Assets#DigitalCurrency#Investments#Savings#Market#Trading#Reserves#Government#FTX#Securities#FortKnox#Economy#PriceDrop#StrategicReserve