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

Резултати

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

Пребарај: #rotaract

当前筛选 #rotaract清除筛选
#HaSab

@Hasab_2016 · Post #44 · 28.02.2024 г., 17:22

ለጋሽ ክንዶች ለሁለተኛ ጊዜ ሊዘረጉ ነው! የክለባችን ሁለተኛ ደም ልገሳ ላይ ለመሳተፍ ዝግጁ? ከታች ባለው ሊንክ ይመስገቡ: https://forms.office.com/Pages/ResponsePage.aspx?id=DQSIkWdsW0yxEjajBLZtrQAAAAAAAAAAAAN__leILWZUMlVBVk5UNlEwOTZJNkFXQTJCNU5FTlBKWS4u For more info: @yared2774 0924751894 Rotaract Family #Rotaract_Kuriftu #Rotary #Rotaract #District9212 #RotaractEthiopia Follow Us: Facebook | Twitter | Instagram | Telegram | LinkedIn

#HaSab

@Hasab_2016 · Post #121 · 25.10.2024 г., 11:26

Multipurpose Court Project Bishoftu,Ethiopia Construction on the new basketball court at Hibret (Tokuma) Elementary School is progressing smoothly and is nearly halfway complete. We're excited about the progress and are on track to achieve our goal. Your support is crucial to ensure the project's successful completion. Our goal is to create a vibrant playground for the children of Hibret School. Play is not a privilege; it's a life skill. Every child deserves a place to play! To contribute and support us please contact us at: [email protected] #Playground#AllDeserveToPlay #Rotaract_Kuriftu #Rotary #100yearsofserviceinafrica #Rotaract #District9212 #RotaractEthiopia Follow Us: Facebook | Twitter | Instagram | Telegram | LinkedIn

STAR VET BOOKS

@starvetbooks · Post #4967 · 22.02.2025 г., 07:01

On Sunday, February 23, 2025, we will be holding a blood donation, dog adoption, and fundraising program in collaboration with Ahadu Rotaract Club at the Red Cross compound around Addis Ababa Stadium starting 9AM To those who want to donate: - Food (Rice) for feeding purpose - Pet beds - Comfy blankets - Medications - Pet toys - Dry pet foods - pet accessaries We will gladly be waiting, the program will be held until 5pm. Come, save lives by donating blood, create a family by adopting dogs! #BloodDonation#DogAdoption#CommunityService#AddisAbaba#Ethiopia#SaveLives#GiveBack#AnimalRescue#Rotaract#AhaduRotaract#Fundraising#CharityEvent https://t.me/starvetbooks

#HaSab

@Hasab_2016 · Post #160 · 07.04.2025 г., 07:58

YES! 🙌 It's a wrap! 🥳 The HaraCoders Bootcamp training, brought to you by the awesome Rotaract Club of Kuriftu 🤝, BuildX Ethiopia , Sira Ale, and Addis Ababa University College of Veterinary Medicine and Agriculture , has been a HUGE success! We're sending out waves of gratitude to everyone involved and a BIG congrats to our fantastic trainees! 🎉 So proud of you all! 🔥 Stay tuned... round 2 might be closer than you think! 😉🚀 #AddisCoders#BuildXEthiopia#TechForAll#EmpowerTheFuture#CodingBootCamp#EthiopianTech#LearnToCode#CodingForChange #Rotary #Rackuriftu #100yearsofserviceinafrica #Rotaract #District9212 #RotaractEthiopia

#HaSab

@Hasab_2016 · Post #152 · 03.02.2025 г., 17:21

🚀 Exciting News! 🚀 The AddisCoders BootCamp is brought to you by BuildX Ethiopia in partnership with Rotaract Kuriftu, SERRALE, and Addis Ababa University! 🎓💻 Together, we’re empowering Ethiopian youth with hands-on web development skills to build the future of tech! 🔥 Stay tuned for more updates! #AddisCoders#BuildXEthiopia#TechForAll#EmpowerTheFuture#CodingBootCamp#EthiopianTech#LearnToCode#CodingForChange #Rotary #Rackuriftu #100yearsofserviceinafrica #Rotaract #District9212 #RotaractEthiopia