Установить свойства виджета в 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
ℹ️Join GODL Pre-Deposit to Split $30,000
💰 During the event, complete GODL pre-deposit on #Gateio CEX, users can share in a
🏆 $30,000 prize pool based on their ranking by pre-deposit volume.
🏆 Everyone is eligible to win a share, ensuring a 100% reward. More GODL — more rewards!
7 November, 2024
$GODL Listing Date!
🔥
3️⃣Days to go until HODL GODL
The Render Network appears to keep depositing $RNDR to CEX after the price surged ~40% (7D).
In the past hour, wallet 0x537 (linked to Render Network) moved 323K $RNDR ($3.36M) to #Gateio and GSR Markets for future CEX deposits.
Since last Jan, the wallet has received 8.1M $RNDR ($67.9M) in total from Render Network and deposited 6.52M $RNDR ($56M) to CEX, often before the price dropped (pic👇).
Follow @spotonchain and set alerts for the wallet and $RDNR for the next important whale activities now:
1. Wallet 0x537: https://platform.spotonchain.ai/en/profile?address=0x53743ac55e434f8aa5097f038b13193497d54d42
2. $RNDR: https://platform.spotonchain.ai/en/token?name=RNDR
Early whale “arthurgayes.eth” moved the first 2T $MOG ($4.41M) to #Bybit & #Gateio 9hrs ago as the price soared!
This whale bought 8.26T $MOG with just 251K $USDC in Sep-Oct 2023;
And still holds 6.26T $MOG (~$14M) in 3 wallets, making an est. total profit of $18.1M (x72)!
Follow @spotonchain and check out the whale’s wallet addresses via this signal: https://platform.spotonchain.ai/en/signal-details/whale-deposited-the-first-2t-mog-441m-to-cexs-for-profit-147215
Three fresh multisigns have withdrawn 43.19M $ENA ($35.68M) from #Gateio and #Bybit in the past week!
With the price surging 28% (7D), these wallets are making $2.05M in unrealized profits.
Are whales bullish on $ENA, a $ETH beta token, thanks to recent Ethereum ETF approval from the SEC?
Follow @spotonchain for set alerts for the multisigns via this token flow: https://platform.spotonchain.ai/en/visualizer?timeRange=4&id=131559&thresholdOption=3
Whale locks in profits after a +185% gain on $ASTER — in just 4 days!
On Sep 18, wallet "0xeE7" spent 1.21M $USDT to buy 2.086M $ASTER at $0.58 via #Aster.
21 hours ago, they deposited 1.043M $ASTER ($1.74M) to #Gateio at $1.67 — likely reclaiming the principal + ~$500K in profit before the market dropped.
Now holding the remaining 1.043M $ASTER ($1.7M) as pure profit.
Follow @spotonchain for more smart money insights.
https://x.com/spotonchain/status/1970073217089102150
🤑Gate.io Startup Answer & Earn @walken_io💵
📝Take the quiz about Walken(WLKN) & Split a $3,000 mega prize!🏆
⏰Ends at 9:00AM, Jul 25th (UTC)
*How to participate:
✅ Join GateioOfficialNews and Walken community
✅Follow @Gateio_Startup & RT the 👉POST
🔛 Click 👉HERE to Participate now
Learn More:https://www.gate.io/startup
#Gateio#gateiostartup
Whale 0x803 (linked to “rektdolphin.eth”) has been steadily accumulating 211.6B $PEPE (now $1.72M) in the past 24 hours, as the price surged back by 17%!
Notably, the whale:
• accumulated PEPE from #Binance, #Gateio, and #Uniswap at ~$0.000007291 (est. cost: $1.54M), now making $173K (+11%) in unrealized profit;
• last withdrew $PEPE only an hour ago and may continue accumulating more tokens.
Follow @spotonchain and set alerts for the whale at https://platform.spotonchain.ai/en/profile?address=0x803c21672a2d3c512bda8c0337dff9a850dd669d
🔥$ASTER up 38% today — who’s fueling the pump?
1️⃣ Whale “0xFB3” deposited 73.95M $USDT into #Gateio and withdrew back 24M $ASTER ($46.6M) ~16hrs ago.
2️⃣ Fresh whale “0x5bd” withdrew 6.72M $ASTER ($13.3M) from #Bybit over the past 16 hours.
3️⃣ Fresh whale “0x8bc” swapped 1.19M $USDT for 595,580 $ASTER in one transaction at $2 per token ~20hrs ago.
4️⃣ Whale “0x5e3” swapped 1,090 $BNB ($1.11M) for 549,194 $ASTER in one transaction at $2 per token ~11hrs ago.
📈🚀 The 24h perp volume on #Aster (@Aster_DEX) just hit $24B+ — over 2x that of #Hyperliquid!
Follow @spotonchain for more updates now!
https://x.com/spotonchain/status/1970785540057530740
As the #memecoin $BRETT price up by 30% (2D), early buyers/insiders are selling for profits!
In the last 32 hours, 5 wallets have deposited 71.76M $BRETT ($9.94M) to #Gateio, #KuCoin, and #Bybit, causing the price to dip after each transfer.
Notably, these wallets:
• belong to a group of 15 wallets that swapped 4.9 $ETH ($14.4K) for 1.86B $BRETT, or 18.6% of the total supply, within 45 minutes of the token creation on Feb 25.
• still have 941.4M $BRETT ($132M) left!
Follow @spotonchain for more updates on #memecoin activities and set alerts for the entity of $BRETT early buyers/insiders via https://platform.spotonchain.ai/en/entity/2061
🍅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
📈#Gateiopartner carnival: the main prize of $12,000 is being played out 🔥
The promotion is active until 11:00 Moscow time on February 24
ℹ️How to earn:
1) Registration on Gate + KYC2
2) Go here and click "Join now"
3) We complete the tasks:
🎁BONUS 1 : Registration + KYC, PrizeStartup voucher for 20 shares
🎁BONUS 2 : Make a deposit of $50, prize from $5 to $10
🎁BONUS 3 : Make a trading volume of $200, split the prize pool of $10,000 depending on the share in the total trading volume
🎁BONUS 4 : Invite users and share the prize pool of $2000
🔗Join now and earn: https://gate.io/fr/campaigns/396?ref=VLJMULHBVA
#Gateio#GateioStartup#Crypto