Установить свойства виджета в 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
👍 Happy Valentine's Day from #Nicegram!
Valentine's Day is all about sharing love, and what better way to do that than by inviting your loved ones to Nicegram? 📲
It's the gift that keeps on giving - not just connecting hearts but also rewarding you with gems! 💎
💗This Valentine's Day, let's make memories: Invite your loved ones to Nicegram and earn gems together!
#Nicegram is the perfect app for those looking to go beyond Telegram's standard functionality, offering enhanced messaging experiences with superior privacy features and customization options 🥰
💌GETA REFERRAL LINK
Happy Valentine's Day, everyone! Let love lead the way 💕
Follow us:✖️X | 📷Instagram | 📖Facebook |💼LinkedIn | 📹YouTube
💸Vietnam Leads in Crypto Adoption, and Nicegram is Right There!
Vietnam's tech-savvy population is spearheading global crypto adoption, and #Nicegram is at the heart of it! ▶️
With 25M global users, including 3.6M in Vietnam, we're connecting the crypto community like never before.
💬 Dive into Sergey Sheleg's insights on leveraging Nicegram for Vietnam's crypto wave, and how we're revolutionizing engagement with web3 features ✉️
👉 READ THE FULL INTERVIEW
Follow us:✖️X | 📷Instagram | 📖Facebook |💼LinkedIn | 📹YouTube
🆕New #Nicegram Update Alert
We're excited to announce our latest update - now running on the fresh and advanced Telegram 10.3.1 version! ⭐️
🌟 Introducing Nicegram Special Tasks:
🔸In the tasks section, you'll find a new option. Tap on it to discover a variety of tasks from advertisers.
🔸Choose any task you like, read the conditions, and complete the required steps.
🔸Once the advertiser confirms your task completion, gems are yours!
Effortlessly track the status of your rewards right from the menu.
It's that easy and fun! 🤡
Get ready to boost your gem earnings with these special tasks from advertisers!✨
🔗OPEN NICEGRAM PROFIT
Follow us:✖️X | 📷Instagram | 📖Facebook |💼LinkedIn | 📹YouTube | 📰Medium
🔄 Introducing Our Ambassadors 🔄
Say hello to our incredible ambassadors who are here to make your #Nicegram experience even more amazing! 🔝
Today, let's shine the spotlight on our first ambassador:
🌈 Kate (Busty Barbie)🌈
Meet Kate, our vibrant ambassador! With captivating charm and unparalleled wit, she injects a burst of fun into Nicegram.
Dive into her delightful presence for great conversations and lasting laughs!🔥
Stay tuned for more updates as we unveil the rest of our ambassadors! 😎
🔗CHECK THE AMBASSADORS
🆕The new #Nicegram update is available NOW!
Here are all of the exciting new features that await you 👇
🔹Update to Telegram 10.3 version
Nicegram now has the latest version of the Telegram source code.
🔹Nicegram Profit is now live!
Now you can earn Gems by inviting friends and completing tasks.
Use these Gems for a variety of rewards - from engaging with AI and creating images, to participating in auctions, or even converting them into cryptocurrency and prepaid cards!
Start exploring all the new possibilities with Nicegram!🔄
UPDATE NOW👇
🛒APP STORE | 🛒GOOGLE PLAY
🎉Join the #Nicegram Community Giveaway!
As we gear up for the upcoming Nicegram Profit, we're bringing you an awesome contest to boost your engagement and rewards! 🔝
📆 Dates: Dec 6 - Dec 14
📝Simple Rules:
🔹Join @nicegramapp
🔹Join @nicegramchat
🔹Chat away! Send 20+ meaningful messages. (Note: No stickers or basic hellos!)
💰 Prizes: 3 winners get 💵 20 USDT each!
💥But wait, there's more! Use your Referral link to invite friends and chat away in Nicegram. More chats, more chances to grab additional rewards!
Get ready to chat, refer, and win! 🏆
🔗OPEN NICEGRAM ASSISTANT
🌟 Exciting updates and exclusive content await you on #Nicegram!
🚀 Follow us on Twitter for the latest news and events before anyone else!
🔗x.com/nicegramapp
📣Don't miss out—join the Nicegram Twitter now! 🌐
Our socials:✖️X | 📷Instagram | 📖Facebook |💼LinkedIn | 📹YouTube
❤️Did you know about Nicegram Navigation?
📌 Here at #Nicegram, we're on a mission to make your journey through Nicegram's world an absolute breeze!
Follow our 🔗@NicegramNavigation for a seamless experience — access all our official social media links, chats, and channels effortlessly 😎
🌐Join us today and simplify your Nicegram journey
🔗https://t.me/NicegramNavigation
❤️Choosing the Best Messaging Experience: Nicegram vs. Telegram 🚀
While Telegram has its strengths, Nicegram pushes the envelope to deliver a superior messaging experience. What sets Nicegram apart?
💬Unleashed Communication:
🔓Access blocked channels & groups, no VPNs required
🔞Experience chat freedom, no blocked conversations
📲Multiple account mastery; juggle personal, business, and more
💡User-Centric Features:
⚙️"Double Bottom" – Conceal your chats and accounts effortlessl
🧠Built-in ChatGPT assistant, LilyAI, ready to assist
🚀Unique chat enhancements: quick replies etc.
🌐Exclusive to Nicegram:
🔹Unique Nicegram assistant
🔹Virtual Сard benefits
🔹 An active Nicegram Community Hub
🔹 Enhanced chat with distinctive and spicy feature
Your chats, upgraded. Dive into the world of #Nicegram🌟
🔗https://nicegram.app
❤️Today’s Fact of The Day is here!
Ready to break the limits? 🚀
Roll up your sleeves because with #Nicegram, you can create an unlimited number of accounts, anywhere, anytime.
📲Separate work and personal contacts, and wear as many hats as you please!
How do you use this limitless feature of ours?
We can’t wait to hear your stories! 💬
🔗https://nicegram.app
Follow us: 🐦Twitter | 📷Instagram | 📖Facebook |💼LinkedIn | 📹YouTube
❤️AI is revolutionizing our world in astonishing ways!
🔬 From detecting intricate health conditions to streamlining business operations, AI is the driving force behind numerous advancements.
📺 Think about the last time you binge-watched a series. Wasn't it AI that recommended it to you on your favorite streaming platform?
✨Such innovations only scratch the surface!
🦾 Among these leaps forward is LilyAI within the #Nicegram app. It's more than just a chatbot; it's your personal companion.
We are always improving LilyAI. It's already unique! 🌟
🔗nicegram.app/deeplink?url=ncg://aiLily
Dive deep into the world of AI with #Nicegram.
Follow us: 🐦Twitter | 📷Instagram | 📖Facebook |💼LinkedIn | 📹YouTube
❤️Level Up with Nicegram
In today’s world of 24/7 online communication, don’t let limitations dim your conversations! 💬
👉 Experience limitless Telegram messaging but on a whole new limitless level with Nicegram’s:
🌍 Global Unrestricted Access
🗣️Access to Blocked Channels and Groups
🤖 Ultimate and unique AI chatbot
📱Multiple Accounts on One Platform
🛡 Secure, Double-layered Encryption
🔄 Instant Voice to Text Transcription and Translations
💳Virtual card Integration
Ready to chat unrestricted, unblocked, and unleashed, whenever and wherever?
Download #Nicegram now and start chatting today!
🔗https://nicegram.app