Установить свойства виджета в 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
👀Educational content, charity and newcomer-friendly tools: An insightful look into the inner workings of a global crypto exchange.
🛡Learn how BingX diverse trading options can help you manage risks and capitalize on opportunities.
#DigitalCurrency
#Cryptonews
#CryptoCommunity
#Cryptolife
🚀 Iran Utilizes Cryptocurrency for Strait of Hormuz Passage Fees
Iran is employing cryptocurrency to collect fees from ships passing through the Strait of Hormuz. According to NS3.AI, TRM highlighted that the rapid nature of digital currency transactions and their operation outside the U.S. banking system complicate efforts by the U.S. to freeze or block these payments in real time.
#Iran#Cryptocurrency#StraitOfHormuz#DigitalCurrency#Shipping#USSanctions#Blockchain
Massachusetts to Establish Bitcoin Reserve
Massachusetts Senator Peter Durant proposes a bill to create a Strategic Bitcoin Reserve. This aligns with initiatives in states like Oklahoma, Wyoming, and Ohio, driving a potential federal reserve plan via executive orders or legislative action. Full details here: Blockspace
#Bitcoin#Crypto#Blockchain#Finance#Investment#Legislation#DigitalCurrency#Innovation#Massachusetts#UTC VC
🚀 Quantum Safe Bitcoin Proposed to Resist Quantum Attacks
Avihu Levy has introduced a concept called Quantum Safe Bitcoin, which is a hash-based transaction design intended to withstand quantum computing attacks. According to NS3.AI, this proposal seeks to enhance Bitcoin's security without altering its fundamental rules. The estimated cost for implementing this design using cloud GPU computing ranges from $75 to $150. However, the complete transaction assembly and broadcast have yet to be demonstrated on the blockchain.
#QuantumSafeBitcoin#Bitcoin#QuantumComputing#Blockchain#Cryptocurrency#CyberSecurity#DigitalCurrency#CryptoInnovation#BTC
🚀 AI TRENDS | Xverse Launches AI-Driven Bitcoin Wallet for Enhanced Transactions
Bitcoin wallet Xverse has announced the introduction of its AI-powered Agentic Wallet, designed to facilitate payments, transactions, and fund management on the Bitcoin network. According to Foresight News, the wallet utilizes Spark for lightning payments and supports machine-payable APIs through MPP, featuring a fully self-custodial architecture.
#AI#Bitcoin#Cryptocurrency#Fintech#Wallet#Blockchain#Payments#MachineLearning#DigitalCurrency#BTC
🚀 Solana Developer Platform Launches Amid Growing Interest in Stablecoin Settlement
The Solana Foundation has introduced its Solana Developer Platform, marking a significant milestone for the network as it reaches 167 million monthly token holders. According to NS3.AI, this development comes as major financial entities like Mastercard are investigating stablecoin settlement on the Solana blockchain. Additionally, Worldpay and Western Union are exploring on-chain settlement and cross-border transfer capabilities.
In a related move, MetaMask has announced that its MetaMask Card now allows American users to spend Solana USDC at any location where Mastercard is accepted. This expansion of services highlights the increasing integration of Solana's blockchain technology into mainstream financial systems.
#Solana#Blockchain#Stablecoin#Crypto#DeFi#MetaMask#USDC#Fintech#CrossBorderPayments#DigitalCurrency#SOL
🚀 Russia Implements Full Ban on Crypto-to-Cash Exchanges
Russia has enacted a comprehensive ban on crypto-to-cash exchanges, marking a significant policy development in the region. According to NS3.AI, this move is part of a broader trend of regulatory changes across Asia, as countries continue to refine their approaches to cryptocurrency regulation. The ban is expected to impact the way digital currencies are traded and used within Russia, potentially influencing other nations in the region to adopt similar measures. This development is one of several key policy shifts observed in Asia this week, highlighting the evolving landscape of cryptocurrency regulation.
#Russia#Cryptocurrency#CryptoRegulation#CryptoBan#DigitalCurrency#Asia#PolicyChange
Avalanche Visa Card Launches Today
Avalanche has officially launched its Visa card to promote cryptocurrency adoption. The card allows users to spend crypto easily in daily transactions, integrating DeFi solutions. This move aims to bridge the gap between traditional finance and the digital currency landscape, enhancing user accessibility to crypto assets. Read more here.
#Avalanche#Crypto#DeFi#Visa#Blockchain#Finance#MassAdoption#Payments#DigitalCurrency
🚀 Swiss Banks Launch Sandbox for Franc-Pegged Stablecoin Testing
Six Swiss banks, in collaboration with Swiss Stablecoin AG, have initiated a sandbox project for a stablecoin pegged to the Swiss franc, set to operate until 2026. According to NS3.AI, the test involves an ERC-20 token on the Ethereum blockchain and will be conducted in a controlled live environment with transaction limits and a restricted participant pool. While the specific access terms and use cases have not been disclosed, an interim report is anticipated in the second half of the year.
#Switzerland#Banks#Stablecoin#Cryptocurrency#Blockchain#Ethereum#FinTech#DigitalCurrency#Sandbox#Finance#ETH
🚀 Authorities Freeze $12 Million in Cryptocurrency Crime Proceeds
Authorities from the United States, the United Kingdom, and Canada have collaborated in a cross-border operation to freeze $12 million in proceeds from cryptocurrency-related crimes. According to NS3.AI, the investigation specifically targeted phishing schemes, highlighting the ongoing efforts to combat cybercrime in the digital currency sector.
#cryptocurrency#cybercrime#phishing#lawenforcement#crossborder#digitalcurrency#crimeproceeds#NS3AI