Установить свойства виджета в 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
📢 PORTFOLIO UPDATE
Congrats to our portfolio company, Meria Finance, on the launch of its app on the Apple Store and Google Play 👏
The team has worked hard to develop an intuitive one-stop platform to easily buy, exchange, withdraw, stake, and lend #cryptocurrencies.
Download the app: ➡️here
BIT x DWF Labs
Crypto Snapshot [23 Dec] 📰
Highlights:
🔸Whales accumulate $726 Million In #Bitcoin
🔸Bank of International Settlements allow banks to hold 2% in #cryptocurrencies
🔸High net-worth investors continue to seek access to #crypto
Full read here.
👀 India, Indonesia and Mexico are the most promising countries for cryptocurrency adoption. This conclusion was made by researchers at the venture capital firm Jump Capital based on the following factors:
▫️ the risk of high inflation / currency instability;
▫️ large flows of remittances;
▫️ immature financial infrastructure / lack of trust in banks;
▫️population;
▫️ the ratio of GDP / national wealth;
▫️ gold reserves;
▫️regulatory and banking environment;
▫️ a tendency to speculation (exchange trading, gambling, etc.).
#cryptocurrencies#research
💰Cryptocurrencies: Last Week Tonight with John Oliver
Another take on #Bitcoin, other #CryptoCurrencies & #Blockchain. A must-watch.
🚀@PerspectiveIX
🌀 http://prs.pctvix.co/TelegramIX
🔗 What is #Blockchain?
A technology that underpins #cryptocurrencies like #Bitcoin and presents new opportunities for how we share data.
🚀@PerspectiveIX
🌀 http://prs.pctvix.co/TelegramIX
Haveno
https://github.com/haveno-dex/haveno
Private and decentralized way to #exchange#Monero for national currencies or other #cryptocurrencies. Haveno uses peer-to-peer networking and multi-signature escrow to facilitate trading without a trusted third party custodian. Disputes can be resolved using non-custodial arbitration. Everything is built around Monero and Tor.
Haveno is the Esperanto word for "Harbor". The project is stewarded by a core Team, currently formed by 2 people: ErCiccione and Woodser. See the FAQ in the wiki for more information about the project
https://github.com/haveno-dex/haveno/wiki/FAQ
Haveno is still work in progress. There are no binaries available at this stage. If you want to test Haveno you have to compile it first (see https://github.com/haveno-dex/haveno/blob/master/docs/installing.md).
Status of the project
At the moment Haveno is only a Proof of Concept. It's already possible to initiate crypto <-> XMR and fiat <-> XMR trades, but the platform still needs a lot of work before being available for public use.
💰📊In the past 24 hours, Ethereum whales have purchased more than 110,000 ETH valued at $341 million!💵😮
#Cryptoenthusiast
#Cryptocurrencies
#Cryptowallet
💰📊In the past 24 hours, Ethereum whales have purchased more than 110,000 ETH valued at $341 million!💵😮
#Cryptoenthusiast
#Cryptocurrencies
#Cryptowallet
Group: ZombieSquad Community
Members: ~14.09K
💢 Username: @zombiesquadhq
Description:
🔥 Come play the game and earn sunlight, with a chance to score some airdrop rewards!
🏷 Tags: #airdrop
#cryptocurrencies#aichatbot#airdrop#crypto
https://lve.to/k1gt8zxptq
⚠️#Google here gave the holder of #cryptocurrencies a dose of anxiety with the news that quantum computers will be able to hack the military-technical cooperation network much earlier than current forecasts.
⚠️ To #crack RSA encryption, you need 20 times less resources than expected (less than 1 million qubits). Modern quantum computers are much weaker, but their power is constantly progressing. According to various forecasts, it will be possible to cross the 1 million cubic meter mark after 2030.👀
💰The Top Ten Cryptocurrencies
1. Bitcoin
2. Ethereum
3. Ripple
Bitcoin jumped back up over the $8,000 dollar mark on 13 April 2018. As this infographic shows, while #Bitcoin is by no means alone in the world of #CryptoCurrencies, it is by far the most valuable #CryptoCurrency, with a total market cap of over $133 billion.
According to figures from CoinMarketCap, #Ethereum is the closest alternative, but with only $49 billion.
🚀@PerspectiveIX
🌀 http://prs.pctvix.co/TelegramIX
❓ Do you own any cryptocurrency?
👍🏻 Yes
🤔 Not yet, but thinking about buying some
👎🏻 No, and I'm not interested at all