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

Резултати

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

Пребарај: #rocky

当前筛选 #rocky清除筛选
Pensive|

@PensivePost · Post #5704 · 03.05.2022 г., 18:13

#iam#Rocky#yourreview#review Love the way you are Hey buddy, yes you, one who is reading this, you may be alone, not having many friends unlike others, not having enough money to live up to your dreams, may be to even fulfil your small and cutest wishes, you might be tied up all day with your course books, stressful office work, those computers and the hectic tasks, you might be feeling like running away from all your problems and just forget about all your worries, those stressful tasks and from toxic people and enjoy the beauty of the wonderful life. Buddy, you are not alone, me, you, all the top CEO’S, the world politicians, world class celebrities, sportsmen and many real life heroes were been in the same stressful situations, Just stay calm, just feel the beauty of nature, love yourself, love the way you are, the way you are living your life. Have some inner peace, don’t be very harsh on yourselves, just believe in your dreams ,focus on your goals, your passion and nothing else. Don’t give a f* about all these f* things, the girl who rejected you, the friend who betrayed you, the relative who keeps judging you, the society which is putting you shame all the time. Just Focus on your dreams, which is going to bring a grand new reality to new. Remember, no matter where you are and what you are, how worse the situation is, always have that smile on your face, which is going to make all the difference. Bye Bye. (Rocky)

Trump's Ear

@trumpsear_tg · Post #2424 · 29.04.2026 г., 14:00

Greta Thunberg's boyfriend. His name is Rocky. They are said to have met in a psychiatric hospital, where Greta did not stay long after her first attempt to visit the Palestinians in Gaza. 🏥🌍 #greta#thunberg#boyfriend#rocky 👂More on Trump's Ear ⚠️

Видеотека 📼

@videotekashow · Post #13839 · 06.07.2025 г., 07:51

«Если окинуть взглядом свою жизнь, готов спорить, о 80% своих поступков вы пожалеете. Но жизнь — это и есть ошибки». Сегодня исполнилось 79 лет Сильвестру Сталлоне. #ВИДЕОТЕКА #SylvesterStallone #Rocky #FirstBlood #Cobra #TangoAndCash #Cliffhanger #DemolitionMan #TheSpecialist #Copland #TheExpendables2 #TulsaKing