Установить свойства виджета в 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
⚡️Catizen Announcement: Animoca Invests in Catizen for Web3 Gaming Expansion
#Telegram#Bombie#Animoca
Animoca Brands has made a major investment in Catizen, a popular Telegram-based game with nearly 50 million players. With a significant community, Catizen is set to host the Bombie airdrop on May 20, 2025, expected to be one of the largest token generation events of the year.
Source: link
@tonlines
Insights on Crypto Developments
🚨 Important updates in the crypto sector:
1. Trump's Crypto Czar, David Sacks, hints at "important announcements" for digital assets soon.
2. KIP Protocol claims support for the LIBRA token by Argentina's president. Backed by Animoca Ventures and involved with the AI project *Open Campus*. Read more
3. Argentine President Mile clarifies his earlier tweet supporting a private startup, stating he lacked details at the time and has since deleted the post after further understanding. Read more
#Crypto#AI#VC#Animoca#Argentina#KIPProtocol#Trump#DigitalAssets#Milei#LIBRA#OpenCampus#Startup#Partnerships#Decentralization#Finance#Blockchain#Tech
🔥Blockchain Life 2024 — starts in a week!
The legendary Blockchain Life 2024 forum will be held in Dubai on October 22-23. 10,000+ participants will discuss strategies for earning on hot trends of autumn 2024.
🎙Speakers
Justin Sun - Founder of #TRON
Paolo Ardoino - CEO #Tether
Yat Siu - Co-Founder of #Animoca Brands
Pascal Gauthier - CEO #Ledger
Dr. Marwan Alzarouni - CEO of Dubai Blockchain Center
Xinxi Wang - Co-Founder of #Litecoin Foundation
Sunny Lu - CEO #Vechain
Arthur Breitman - Co-Founder of #Tezos
Eowyn Chen - CEO of #TrustWallet
🎓Forum program
The forum program includes keynote speakers, panel discussions, and master classes. You will be able to learn about the latest trends in the cryptocurrency sphere, innovative blockchain technologies, and effective trading strategies.
⚡️The exhibition will bring together leading mining companies providing equipment and services, as well as startups presenting their projects to investors.
⚡️Startup Pitch is a unique opportunity for startups to present their ideas to investors and funds.
⚡️Afterparty — a legendary event featuring a world-famous musician🎵Alan Walker, where you can connect with industry leaders in an informal setting.
👤Why should you go?
✔️ You will learn how to make money on cryptocurrencies and #Web3, regardless of which direction the market is moving.
✔️ You will hear inside information about what to invest in this fall and what is better to sell.
✔️ Traditionally, #BlockchainLife discusses cryptocurrency trends on average six months before they enter the masses.
✔️ All the industry leaders ( #Tether, #Tron, #TrustWallet, #Ledger, etc.) are coming to the forum, and you will be able to find the necessary contacts among the top community.
✔️ You will be able to communicate with the owners of cryptocurrencies that you have in your portfolio
📆When: October 22-23, 2024
📍Where: Festival Arena, Dubai, UAE
Registration:blockchain-life.com
You still can buy a ticket with 🛍 discount from our channel using the promo code: TONEVENTS
#TON#BTC#ETH#SOL#crypto#forum#networking
🪙October 22-23 — Blockchain Life 2024 in Dubai
The legendary Blockchain Life 2024 forum is returning to Dubai on October 22-23. As Dubai increasingly asserts itself as a global crypto hub, #BlockchainLife2024 will undoubtedly become the central crypto event of the year, gathering the top industry representatives from around the world in the crypto capital.
The bull cycle has already begun, but the long-awaited peak of growth is still ahead, so forum participants have a great opportunity to maximize their income.
More than 10,000 people from 120 countrieswill meet at the forum to explore new earning opportunities.
🎙Speakers
Justin Sun - Founder of #TRON
Paolo Ardoino - CEO #Tether
Yat Siu - Co-Founder of #Animoca Brands
Pascal Gauthier - CEO #Ledger
Dr. Marwan Alzarouni - CEO of #Dubai Blockchain Center
Xinxi Wang - Co-Founder of #Litecoin Foundation
Sunny Lu - CEO #Vechain
Arthur Breitman - Co-Founder of #Tezos
Eowyn Chen - CEO of #TrustWallet
Sasha Plotvinov - Founder of #Notcoin💎
🎓Forum program
The forum program includes keynote speakers, panel discussions, and master classes. You will be able to learn about the latest trends in the cryptocurrency sphere, innovative blockchain technologies, and effective trading strategies.
⚡️The exhibition will bring together leading mining companies providing equipment and services, as well as startups presenting their projects to investors.
⚡️Startup Pitch is a unique opportunity for startups to present their ideas to investors and funds.
⚡️Afterparty — a legendary event featuring a world-famous musician🎵Alan Walker , where you can connect with industry leaders in an informal setting.
📆When: October 22-23, 2024
📍Where: Festival Arena, Dubai, UAE
Registration:blockchain-life.com
🎫Buy your ticket now at the lowest presale price with promo codeTONEVENTS👉
#BTC#TON#ETH#conference#blockchain#forum#networking