TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

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

Hashtags

Резултати

Пронајдени 3 слични објави

Пребарај: #makeadifference

当前筛选 #makeadifference清除筛选
NewUU Student Council

@newuu_sc · Post #1460 · 08.02.2025 г., 07:37

🌍 SDG Week: The SDG Nexus – Connecting People and Purpose 🌱 Get ready for an inspiring journey towards a sustainable future! 🌏✨ Join us at Webster University in Tashkent for SDG Week, where you’ll engage with global experts, take part in interactive workshops, and explore how YOU can make a difference in achieving the Sustainable Development Goals. 📆Date: February 10-12 📍Location: Webster University in Tashkent 🕛Time: 12:00 p.m. What to Expect? 📅Day 1: Opening Conference & Networking 🎤 Kick off SDG Week with a powerful conference featuring 5 international universities, a United Nations representative, and leading experts in the field of SDGs. 🤝 Connect with like-minded individuals passionate about sustainability and change. 📅Day 2: Eco Health & Sport Day 🌱 Learn from eco-activist Urikguli (Mutabar Xushvaqtova) in an engaging workshop on environmental sustainability and its impact on our well-being. ⚽ The session will be followed by exciting sports matches to promote health and sustainability. 📅Day 3: Hands-On Workshops & Action Planning 💡 Dive deeper into real-world solutions through interactive workshops, where you’ll develop actionable strategies to contribute to sustainable development. 🍕Special snacks will be provided between networking sessions!🤫 🚀Want to actively contribute to the event? If you have an idea, project, or expertise related to the SDGs and would like to be a part of the program as a speaker, organizer, or contributor, fill out this form: 📢Contribute to SDG Week:https://forms.gle/ReaaTpPMP5W41KwW8 🔗Register as a participant:https://forms.office.com/r/QVFg4ZFZy8?origin=lprLink 📢Join the SDG Club:https://t.me/sdgclubwebster #SDGWeek#SustainableDevelopment#MakeADifference#PeopleAndPurpose

INHA University in Tashkent

@inha_uz · Post #8528 · 20.01.2025 г., 12:05

🌟 Join Us in Supporting the Children’s Hospice! 🌟 🗓Date: 25th of January 📍 Gathering Point: INHA University at 9:00 AM This event is dedicated to bringing love, care, and support to children in the hospice during their most challenging times. Let's come together to make a difference in their lives! ❤️ Your contributions and time as a volunteer can truly bring hope and smiles. 💬How to Help: ✅ Donate: Every little contribution matters 9860 3501 4923 6621(Aleksandra Kim) ✅ Volunteer: Be part of this meaningful event. For more details: @iut_charityy Let’s create a wave of kindness and show these children that they are not alone! 💕 #CharityEvent#ChildrenHospice#Volunteer#IUTCharity#MakeADifference

Real Eco Committee

@real_eco · Post #4 · 15.04.2026 г., 07:56

🌱 Join our Eco Committee! Want to make a real difference for the environment? 🌍💚 If you're interested in being part of our project, come to our Thursday school eco volunteering meeting! Let’s work together for a greener future 🌿✨ #EcoCommittee#EcoClub#GoGreen#Sustainability#SaveThePlanet#EcoFriendly#SchoolLife#Volunteer#ClimateAction#GreenFuture#EnvironmentalAwareness#ActNow#StudentsForChange#MakeADifference#EcoWarriors