Установить свойства виджета в 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
Upcoming Airdrops Alert! 🚀
Hey everyone! 🎉 If you missed out on the Dogs airdrop, don’t worry! There are some exciting new airdrops coming up that you won’t want to miss. Check out these potential big earners:
1. Major🌟
1. X Empire 🏰
3. Cats🐈
4. Memefi🎭
-Confirmed Listing Date: October 9th
-All WILL BE LISTED IN ABOUT A MONTH TIME , SO JOIN AND GET FREE TOKENS BEFORE ITS TOO LATE!!!
#Airdrops
🎁 The #giveaway with 4EVERLAND has officially ended! A big thank you to #TokenPocket for their support and to all participants.
👇🏻Keep an eye out for upcoming thrilling #airdrops and don't forget to claim your $4EVER points at: https://dashboard.4everland.org/quest/tp
🥳We are thrilled to announce that UXLINK has made strategic partnership with @LumozOrg
to build Social Growth Layer(SGL) together!
Our ecosystem fund @UFLY_Labs
will invest @LumozOrg and we will empower Lumoz social growth & business development globally especially in Japan and Korea market & community.
💰Lumoz native token $MOZ will be #TGE on CEXs soon and we will make ONE MILLION dollar value #Airdrops to qualified $UXLINK holders and stakers!
Lumoz is the leading Modular Compute Layer for ZK & AI. Lumoz uses PoW mining mechanism to provide computing power for Rollup, ZK-ML and ZKP verification.
Please stay tuned for our updates!❤️
Channel: Legit Airdrop ️
Members: ~142.24K
💢 Username: @legit365airdropss
Description:
Welcome dear subscribers! We will do our best to share the legit airdrop campaigns timely. If You Need Any Airdrop Project Promotion Then Contract here @Legit365airdrop1 Buy ads: https://telega.io/c/legit365airdropss
🏷 Tags: #airdrop
#airdrops#cryptocurrency
https://telegramchannels.me/channels/legit365airdropss
$ORB and $MOZ #Airdrops done just now, #UXLINKseason2 stakers please kindly check your wallet address to get the token❤️https://arbiscan.io/address/0x0698e377ca9dbfb5c77503d611c6f1f38cf46ba2
#Airdrops Are Making Millionaires In Crypto – Here’s How [Full Guide Cosmos, LUNA & More]
#cryptogemtokenshttps://cryptogemtokens.com/airdrops-are-making-millionaires-in-crypto-heres-how-full-guide-cosmos-luna-more/
Phantom Wallet Dismisses Token Rumors
Phantom Wallet team clarifies: no plans for a native token or airdrop. Focus remains on improving the token and app discovery mechanism. More details: Read here
#Phantom#airdrops#wallets#Crypto#VC