Установить свойства виджета в 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
⭐Expression: “Easy peasy Japanesey!”
When something is so simple you can do it with your eyes half-closed,Americans sometimes joke and say:
👉 “Easy peasy Japanesey!”
It’s playful, childish, and super informal, perfect when you want to sound fun and light-hearted.
Example:
A: Can you fix this for me?
B: Sure. Easy peasy Japanesey!
Meaning: “Piece of cake. No big deal.”
#Expression
#Teamjimmy
@Sirjimmy
🌍Around the world in expressions!✈️
🇨🇭“I’m Switzerland” – Staying neutral like a pro.
🇫🇷“Excuse my French” – Oops… did I just swear? 😅
🇬🇷“It’s all Greek to me” – Totally incomprehensible! 🤯
🇳🇱 “Let’s go Dutch” – Sharing is caring (and paying!) 💸
💬 Which one is your favorite? Or do you have your own “worldly” saying?
#Expression
#Teamjimmy
@Sirjimmy
🔵 Today’s Expression:
“Whatchamacallit” /ˈwɒtʃəməˌkɔːlɪt/
“Whatchamacallit” is a fun, casual word we use when we can’t remember the name of something or when the name simply doesn’t matter.
🔹Meaning
A playful replacement for the name of an object you can’t recall.
🔹Examples
🔹Pass me that whatchamacallit...the phone holder.
🔹Do we still have that spicy whatchamacallit sauce?
🔹I need the whatchamacallit to connect my laptop to the TV.
#Expression
#Teamjimmy
@Sirjimmy
❤️ It's my turn to + (verb)
✍🏻« When stating 'my turn' you are telling someone that it is time to change position or position focuses on to you.»
💭Here are some examples:
🔷"It's my turn to walk you home.”
🔷"It's my turn to do laundry."
🔷"It's my turn to take out the trash."
🔷"It is my turn to roll the dice."
🔷"It is my turn to attempt solving the problem."
#Expression
#Teamjimmy
#sirjimmy
The point is that + (subject + verb)
✍🏻«By stating 'the point is' you are stating in your opinion the meaning about what is actually happening.»
📍Here are some examples:📍
📕"The point is that if you study you will do well in school."
📕"The point is that she does not understand."
📕"The point is that the world would be a better place."
📕"The point is that snakes can be dangerous."
📕"The point is that leaving a baby alone is not a good idea."
📕"The point is that if we do not leave now we will be late."
📕"The point is that she needs to be more responsible."
◽️◽️◽️◽️◽️◽️◽️◽️◽️
#Expression
#Teamjimmy
#sirjimmy
💢 Ahead Of One's Time
🎨 Meaning:
🍃 In advance of current ideas and trends.
🎨 Usage:
🍃 Some people describe Albert Einstein was a physicist ahead of his time.
〰〰〰〰〰〰〰〰〰〰〰〰
Level: Intermediate_Advanced
=========================
#Idiom#Expression#Ahead
@TowardDiscoveringEnglish
Expressionlar va ulardan resurslar so'rovlarida foydalanish
Talablarga binoan, siz kutgan mavzu - Expressionlar. Barchaga ma'lumki, database dan kelayotgan ma'lumotlarni dinamik holatda filterlash, saralash unchalik ham oson emas. Ushbu mahorat darsimizda, Sultonbek sizlarga expression/query lar bilan ishlashning yangicha usulini taqdim etmoqchi. Eng qizig'i shundaki, bizning speaker mavzudan ilhomlanib, ushbu amaliyot uchun yangi kutubxona ham ishlab chiqishga ulguribdi. Judayam qiziq, sinab ko'ramiz-a, nima deysiz?
Barchangizni ushbu mahorat darsida kutib qolamiz. Kirsangiz xursand bo'lamiz, kirmasangiz hafa bo'lish yo'q )
Sana: 22-yanvar, 20:00
Havola: Zoom
Speaker: Sultonbek Rakhimov
#expression#linq#filtering#sorting
.NET Uzbekistan Community
➖➖➖➖➖➖➖➖➖➖
Telegram | Instagram | Youtube
Do you know someone who always thinks that everyone else has a better life than them?! 🙄😅 Scroll through the images to find out how to use ‘the grass is always greener on the other side’ 🌱, and don’t forget to answer the questions on the last slide!
EXTRA: Could walking 7,000 steps a day could improve your mental health? 🚶 Click the link in our bio to find out and learn some useful vocabulary in the process! 📰💚
Image: Getty
#vocabulary#learnenglish#englishlanguage#expression#idiom#proverb#englishclass#speakenglish
Master Class in Koblenz,
Germany 🇩🇪 2025 @rsg.koblenz
Мастер-класс международного
Проекта „Art in Sport”
В Кобленце, Германия
#Dancing#Expression
#Artistic#Emotionality
#LiubovBarykina#Choreographer
#PersonalCoach#ArtlnSport
For individual training sessions
And master classes, please
Contact us via private message
👍👍👍🌼🌼🌼💃🏽💃🏽💃🏽
По проведению
Мастер-классов,
Постановок и
Индивидуальных занятий
Свяжитесь со мной
В личном сообщении 👍
You know when somebody just WON’T change their ways? 😠 We’ve got an English expression for that! ✅
Scroll through the images to find out how to use ‘You can’t teach an old dog new tricks.’ ❌🐶
Can you use it in a sentence – and do you have a similar expression in your language? 👇👇👇
MORE: If you'd like to learn some more animal idioms, like 'rabbit on 🐰' or 'as sick as a parrot 🦜', click the link in our bio!
Image: Getty
#trick#proverb#learnenglish#vocabulary#learnenglish#englishlanguage#expression#idiom#englishclass#speakenglish