@MostInspiring · Post #1966 · 04.04.2024 г., 02:10
Must watch. #MustWatch What matters the most is.. Not who's mistake but whose life
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
Пребарај: #mustwatch
@MostInspiring · Post #1966 · 04.04.2024 г., 02:10
Must watch. #MustWatch What matters the most is.. Not who's mistake but whose life
Hashtags
@MostInspiring · Post #1515 · 16.10.2020 г., 09:01
#MustWatch @MostInspiring Video Click to Join 👇👇👇👇 You will certainly Experience the good Feeling after seeing this Video
Hashtags
@rusembcy · Post #1341 · 21.11.2023 г., 06:17
#MustWatch To fully understand the genesis of the current situation in Ukraine, how the rise of Neo-Nazism came to be and how the far-right Russophobic ideology and groups gained power over a brotherly nation one must take a retrospect view. 📣 World renowned filmmaker and actor, Academy award winner Nikita Mikhalkov tells and explains just that, with proven facts and archival footage to show the truth, in an emergency hour-long episode of his author's programme BesogonTV. The Western mainstream media will never report on these facts, sweeping under the rug anything that damages the current anti-Russian narrative, hoping the audiences have no recollection of the sequence of the events. Watch to jog your memory. Warning: the video contains sensitive images, viewer discretion advised.
Hashtags
@MostInspiring · Post #760 · 04.05.2019 г., 02:51
⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️ One of the best videos ever! Absolutely brilliant in conveying the most needed message of today with no words! We wish this video goes viral across India and the world to create an awareness where education is sold. @MostInspiring #MustWatch
Hashtags
@MostInspiring · Post #655 · 31.03.2019 г., 04:49
Will Power #mustwatch @MostInspiring
Hashtags
@MostInspiring · Post #490 · 13.02.2019 г., 15:01
#MustWatch@mybestcollection
Hashtags
@MostInspiring · Post #329 · 23.12.2018 г., 22:37
@MostInspiring #mustwatch
Hashtags
@MostInspiring · Post #313 · 19.12.2018 г., 23:18
#MustWatch @MostInspiring
Hashtags
@positivenewss · Post #232 · 23.06.2020 г., 09:17
What is real kindness #mustwatch @Highimpact
Hashtags
@primevisa_uz · Post #205 · 21.07.2022 г., 04:43
Bizga ham nasib qilsin 🙌 #mustwatch
Hashtags
@positivenewss · Post #143 · 12.04.2020 г., 05:07
Amazing Video 🔗👆 #MustWatch
Hashtags
@MostInspiring · Post #133 · 24.10.2018 г., 00:06
@MostInspiring #MustWatch
Hashtags