Установить свойства виджета в 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
#TMONK (TON) 💎
Telegram Monk is a meme? Not only this but something greater it's a meme with a bold and ambitious vision inspired by Pavel Durov, because Durov is also a @monk.
This is a CTO, the guys on the team are working hard to prepare us for something insane.
The team is rebranding the entire site, logos, profiles.
📱 Telegram: https://t.me/Tg_Monk
📱: https://x.com/TmonkMonk
📱 NEW WEBSITE: SOON
👍 Ca: EQBikuxOnMkU4XNSVGQCbg46lk5d8vuhzDQtcDOJOcjaIvkV
😄Chart: https://dexscreener.com/ton/EQBikuxOnMkU4XNSVGQCbg46lk5d8vuhzDQtcDOJOcjaIvkVb
✅TMONK DAILY TASK ✅
1️⃣ Join on: https://moontok.io/coins/telegram-monk , add TMONK on watchlist ⭐️ and vote 🚀.
2️⃣Join on: https://ntm.ai/token/EQBikuxOnMkU4XNSVGQCbg46lk5d8vuhzDQtcDOJOcjaIvkV?graph=EQDOfAMeJVkC1Q0F1SofSqKf4YLxaj41YumJ4tnER7RTH_GH and vote TMONK 🚀.
3️⃣Join on:https://www.geckoterminal.com/ton/pools/EQDOfAMeJVkC1Q0F1SofSqKf4YLxaj41YumJ4tnER7RTH_GH , add TMONK to Watchlist ⭐️ and vote 🚀.
4️⃣Join in X: write #TMONK in the search bar, click latest and leave a like, a comment and a repost.
5️⃣ Invite all your friends to join our project. TG: https://t.me/Tg_Monk X: @TMonkOfficial X-partnership: @TMonkPartners.
6️⃣ Participate in all raids.
We will go viral, we will become a point of reference in the TON ecosystem, you are incredible, you are unique, we will achieve unimaginable goals.
We are TMONK.
Special competition and giveaway for our NFT holders
🔥Earn Rewards for Social Media Tasks📲
🔗dexpert.io/activity
📆 2024/06/12 ~2024/06/18
Connect your wallet to start. Points System:
📌Benefits for NFT Holders: Golden Pass(Unlimited bot usage up to 6 months), 8000 D-points in the first missions, and 1500 D-points everyday!
📌Other Users: 2000 D-points in the first missions, and 600 D-points per wallet per day.
⁉What can D-point do?
Our Official link: linktr.ee/dexpert
Token Creation Bot: t.me/DexpertThorBot
Sniper Bot: t.me/DexpertOdinBot
#dexpert#Tmonk
Announcing Partnership the $TMONK
• After a while, #TMONK is a good team, They have a strategy for long-term development on #TON
• #DashApe Will work and develop with the team, the team's goal is at the lowest level of 5M, there are many more features to be released soon
• You can feel free to buy $TMONK now, as they will soon reach 500K this month
• Mc 45k is low now, Buy and hold for long term
TG : https://t.me/Tg_Monk
Chart : https://www.geckoterminal.com/ton/pools/EQDOfAMeJVkC1Q0F1SofSqKf4YLxaj41YumJ4tnER7RTH_GH
Hello all new Monks!
Welcome to #TMONK❔
The only place on TON where #memecoin#charity and #crowdfunding coexist!
Where you can see realized the principles and ideas of Durov and Telegram 💎🔥
Be sure to read the pinned messages at the top ❔❔
However, If you're new to #TON Blockchain, feel free to ask all you need!
Stay tuned!
WE ARE CREATING AN ECOSYSTEM
❔ Follow both our X account❔
@TMonkOfficial
@TMonkPartners
❔Follow and comment each post in our channels❔
❔https://www.tgmonk.org/project/
❔https://t.me/TmonkAnnouncements
❔https://t.me/AthenaMemeHubChat
❔https://t.me/AthenaDexFi_en
❔https://t.me/AthenaMemeHub
❔https://t.me/bestcoins_club
❔https://t.me/CryptoSharingHub
TMONK Team.
💎$TMONK #RoadToMEMELANDIA# Contest💎
1️⃣st 100 token $TMONK
2️⃣st 70 token $TMONK
3️⃣st 30 token $TMONK
👀5 more participants will get WL spot in upcoming private sale of our partner ATHENA DexFI
How to enter the #contest :
1️⃣Follow @ https://x.com/TMonkPartners?s=35
2️⃣ Join telegram groups:
✔️https://t.me/RoadToMEMELANDIA
✔️
https://t.me/TmonkAnnouncements
3️⃣ Under the tweet of this contest
present on X https://x.com/TMonkPartners?s=35
Answer with a post with original and funny TMONK memes ( Video, gif or stickers are welcome as well )
You can create as many as you want .
Share your post to atleast 3 real yours friends(we will check if you don’t respect this rule or share to someone that isn t your friend)
Remember to put also
@ton_blockchain and @telegram and to use hashtags #MemeContest#freedom#crowdfunding#charity#tmonk
4️⃣. Submit your X entry under the comments of relatived post of this two groups
🖥https://t.me/RoadToMEMELANDIA
🖥
https://t.me/TmonkAnnouncements
The 8️⃣ winners will be chosen by the team
Valid for 4️⃣ days
Ends 25.04.2024 15 utc UTC
GOOD LUCK TMONKERS
🤝 $TON UNIQUE: TMONK x $GROYPER
Nr. 1! 🐸💎
The partnership that celebrates uniqueness is here! TMONK the GROYPER are joining forces!
Two powerful brands, one dominating narrative. Growth on TON has never been this #Bullish and unmistakable.
Join the Uniqueness:
MONK:
💬Tg_Monk
tmonk-ton.com
https://dexscreener.com/ton/eqdofamejvkc1q0f1sofsqkf4ylxaj41yumj4tner7rth_gh
GROYPER
🐦@groyp_on_ton
💬GroyperonTon
https://dexscreener.com/ton/EQDPtuvcV-lq_i3aYT9ZCEOKIj4EwcrnsBJjMJmQpehBeSPD
#TMONK#VYNX#Groyper#TON#Nr1
American $IDIOT × $TMONK Digital Creation Contest 🚨
Two legendary TON meme coins — $IDIOT & $TMONK — unite to launch a contest for all artists, meme-makers, designers and animators.
Your task: create digital art or short videos inspired by the words of Pavel Durov.
🎭 Themes (choose one or mix them):
✨#LeadByExample → Show discipline through actions, not words.
✨#FocusOnThePositive → Spread strength & positivity, even in hard times.
✨#PrioritizeConscience → Highlight morals and conscience as timeless values.
🖌 Creative Direction:
– Any medium: illustration, animation, photo art, 3D, short video.
– Include $IDIOT & $TMONK in your work (graffiti, sticker, cameo, clothing, etc.).
– Be creative, original, and make it memorable.
🏆 Prize for 1 Grand Winner:
🎩 TOP HAT — Uncle Sam (Telegram gift from American $IDIOT)
📖 Special e-book created by the TMONK community
📌 How to Enter:
Post your creation under this official post and
Tag @TmonkMonk & @AIdiot4547.
Share also in:
▪️t.me/Tg_Monk
▪️t.me/AmericanIdiotBackup
⏳ Timeline:
– Submission deadline: 10.10.2025 (Pavel Durov’s birthday)
– Winner announced: 11.10.2025
⚖️ Judging (100 points total):
– 50 pts → Community score (likes, tags & shares on X)
– 50 pts → Jury score (5 judges) on:
• Creativity & originality
• Connection to theme
• Clever inclusion of $IDIOT & $TMONK
👉 Show your vision. Spread Monk values. Leave your mark.
#LeadByExample#FocusOnThePositive#PrioritizeConscience
#TON#TMONK#IDIOT