Установить свойства виджета в 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
🪙Tomarket Early Adopters Reward
After passing through many phases, Tomarket is getting closer to the long-awaited listing day that all Tomarket users have been looking forward. You still have plenty of time to earn more TOMA through several methods.
Tomarket also appreciates the early adopters who have supported this project from the beginning until now.
🥇Tier 1: Joined before July 14, 2024 - Earn an extra 20% TOMA based on your holdings during the TGE snapshot.
🥈Tier 2: Joined before July 31, 2024 - Earn an extra 15% TOMA.
🥉 Tier 3: Joined before August 31, 2024 - Earn an extra 10% TOMA.
😄What are you waiting for?
Log in now and claim your reward!
Listing Date: December 20
#Tomarket#TOMA
Listing $TOMA is coming!
December 20🪙
Celebrate the exclusive Giveaway 💰 — use the link below to open a chest and win up to 🪙1,000 TOMA! 🎁
Don't miss this chance to grab more TOMA before the big listing! 🚀✨
#Giveaway#TOMA
#Molise
Indagati per abuso di ufficio il presidente della Regione Donato #Toma e alcuni suoi assessori. I fatti, avvenuti tra il 2020 e il 2021, ruotano attorno all'incarico di commissario straordinario del Consorzio per lo sviluppo industriale di Campobasso-Bojano
@UltimoraPolitics
Fewer than 50,000 Golden Tickets left!
Already part of the club? 🪙 If you're farming $TOMA, don’t miss out — grab your lucky ticket for just ⭐️250 Telegram Stars before the snapshot on December 18.
Mark your calendar: listing goes live on December 20!
#Tomarket#TOMA#Airdrop
💎TON check-ins are available in Tomarket🍅
Now you can get as much Tomarket 🌟 Stars as you wish without playing machine and get the highest level of League easily!
Don't miss this opportunity!😄
#Toma#TON#Airdrop#Bitget
🍅 $TOMA's official listing date: 20th December
It's official. Early and active players will be happy.
And remember, your level will be the key.
Check your TOMA balance!😄
#TOMA#Tomarket#Airdrop#listing
#Italia
❗️ Perde forza l'appello dei governatori a Draghi: dopo il no dei 3 governatori di #FdI|ECR, si sfilano anche i forzisti #Cirio, #Bardi, #Toma e #Occhiuto.
@UltimoraPolitics
🍅Pre-deposit 🪙$TOMA on CEX and $200,000 bonus
#Tomarket is preparing to enter two leading exchanges — #Gateio and #Bitget!
💰$TOMA Listing Confirmed on Gate.io:
Starting from December 20, 2024 at 12:00 PM (UTC), $TOMA trading will start on the Gate.io exchange.
💱$TOMA output is open on Bitget:
Pre-deposit for $TOMA opens on Bitget exchange on December 13th at 8:00 UTC. Token holders can deposit their assets without gas fees and get a chance to earn up to $100 in $TOMA tokens from a total prize pool of $200,000 !
The promotion periodis from December 13 to 18 — act quickly!✈️
Participation in the promotion is carried out on a first come, first served (FCFS) basis, so make sure to contribute your $TOMA and become one of the lucky ones who receive additional rewards!
🪙Go to the app, open the Airdrop tab and choose the method of sending tokens.
ℹ️ To withdraw you will need your TOMA address on the Bitget exchange: Bitget\TOMA\Deposit (Aptos network) + your UID
#Tomarket#TOMA#Gateio#Bitget#CryptoNews#Airdrop
⏺PixelSwap Farming Pool in🍅Tomarket
#PixelSwap recently partnered with the well-known social platform Tomarket, which allows Web2 users to easily transition to Web3 through games, earnings and trading.
There is a new farming pool available in 🍅#Tomarket app where you can get a share of $PIX depending on how much $TOMA you contribute to the pool. The pool starts tomorrow at 10:00 UTC🕓
✖️Use TOMA to get PIX!
#TOMA#PIX#earn#farming