@QuietWorld · Post #7102 · 24.12.2019 г., 01:35
🗾 How often we fail to realize our good fortune in living in a country where happiness is more than a lack of tragedy. #quotes#gratitude @quietworld🍃
Hashtags
TGINSIGHT SIMILAR POSTS
Изворен канал @pythonotes · Post #381 · 23 окт.
Установить свойства виджета в 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
Пребарај: #gratitude
@QuietWorld · Post #7102 · 24.12.2019 г., 01:35
🗾 How often we fail to realize our good fortune in living in a country where happiness is more than a lack of tragedy. #quotes#gratitude @quietworld🍃
Hashtags
@QuietWorld · Post #6773 · 23.10.2019 г., 08:30
🔖 Appreciate where you are in your journey, even if it's not where you want to be; every season serves a purpose. #life#gratitude#wisdom @quietworld🍃
Hashtags
@QuietWorld · Post #6625 · 02.10.2019 г., 03:52
"How cool is it that the same God who created mountains and oceans and galaxies looked at you & thought, the world needed one of you, too." #quotes#reminder#gratitude @quietworld🍃
Hashtags
@QuietWorld · Post #6904 · 14.11.2019 г., 14:55
#positivity#gratitude @quietworld🍃
Hashtags
@QuietWorld · Post #6811 · 28.10.2019 г., 13:01
We love those people who give with humility, or who accept with ease. #kindness#gratitude @quietworld🍃
Hashtags
@QuietWorld · Post #7145 · 14.01.2020 г., 00:32
Life is Simple First, Don't bother with other people's lives, no need to comment much, no slander here and there, no need to make fun of it.. Second, Live within your means. Don't torture yourself just to follow trends or impress people. Third, Just enjoy your life and be the best you can be. Be grateful for what you have, and do what you want. Fourth, Don't listen to what people say. Even if that person insults you. Just remember, you didn't ask that person to feed you anyway. Have a blessed day ☺️🌻 #life#gratitude#attitude @quietworld🍃
Hashtags
@the_life_tips · Post #16090 · 11.05.2025 г., 04:30
Happy Mother's Day!🤰🤱🎉 Today, we celebrate the strength, wisdom, and unconditional love of all mothers. A mother is not just someone who gives life, but someone who inspires it. She teaches us resilience through her sacrifices, courage through her actions, and love without limits. Take a moment to appreciate the woman who shaped your beginnings. And if you're striving for greatness—remember, behind every strong person is often a mother who believed in them first. Honor her. Thank her. Make her proud. #MothersDay#Gratitude LIFE TIPS✅️
Hashtags
@news_and_tips · Post #825 · 21.01.2023 г., 02:30
Hello 👋 everyone! Today is my birthday🍰 and I just wanted to take a moment to thank each and every one of you 🫵 for being a part of my journey. Your support and encouragement means the world to me❣. I'm excited to continue creating content and sharing it with you all. Here's to another year of growth and adventure! Cheers! 🥂 #birthday#gratitude
Hashtags
@QuietWorld · Post #6821 · 30.10.2019 г., 06:30
"I don't have to chase extraordinary moments to have happiness – it's right in front of me if I'm paying attention & practicing gratitude." #happiness#gratitude#reminder @quietworld🍃
Hashtags
@QuietWorld · Post #7696 · 25.11.2020 г., 00:45
Simple Pleasures in Life #life#gratitude#beauty @quietworld🍃
Hashtags
@QuietWorld · Post #7181 · 04.02.2020 г., 07:41
when life gets hard, count your blessings.. it might not solve all your problems, but it'll help you go through the hard times easier and better..🍃 #afterthoughts#thoughts#gratitude#attitude @quietworld🍃
@QuietWorld · Post #6856 · 04.11.2019 г., 13:33
Appreciate where you are in your journey, even if it's not where you want to be - because every season serves a purpose. #life#quotes#assurance#gratitude#happiness @quietworld🍃