Установить свойства виджета в 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
#ML
😎
FREE RESOURCES TO LEARN MACHINE LEARNING
Intro to ML by MIT Free Course
Machine Learning for Everyone FREE BOOK
ML Crash Course by Google
Advanced Machine Learning with Python Github
Practical Machine Learning Tools and Techniques Free Book
Python Machine Learning for beginners
-----
Main channel: @repo_science
Coupons: @freecoupons_reposcience
-----
#ML
🧠
Machine Learning Expert
El aprendizaje automático es un vasto campo con muchos conceptos clave que conocer. Nuestro curso intensivo cubre todos los componentes básicos que necesita para sumergirse en el aprendizaje automático del mundo real.
✍️Ryan Doan | Ex-Amazon ML Infrastructure Engineer
🌐En
📆2022
🔗Link
-----
Main channel:@repo_science
Coupons:@freecoupons_reposcience
-----
#ml
What’s Really Going On in Machine Learning? Some Minimal Models—Stephen Wolfram Writings
https://writings.stephenwolfram.com/2024/08/whats-really-going-on-in-machine-learning-some-minimal-models/
#ml
Meta's second version of segment anything.
https://github.com/facebookresearch/segment-anything-2
They have a nice demo:
https://sam2.metademolab.com/
#ml
I was searching for a tool to visualize computational graphs and ran into this preprint. The hierarchical visualization idea is quite nice.
https://arxiv.org/abs/2212.10774
#ml
Like a dictionary
Kunc, Vladim’ir, and Jivr’i Kl’ema. 2024. “Three Decades of Activations: A Comprehensive Survey of 400 Activation Functions for Neural Networks.” arXiv [Cs.LG], February. http://arxiv.org/abs/2402.09092.
#ml
I got interested in satellite data last year and played with it a bit. It's fantastic. The spatiotemporal nature of it brings up a lot of interesting questions.
Then I saw this paper today:
Rolf, Esther, Konstantin Klemmer, Caleb Robinson, and Hannah Kerner. 2024. “Mission Critical -- Satellite Data Is a Distinct Modality in Machine Learning.” arXiv [Cs.LG], February. http://arxiv.org/abs/2402.01444.
#ml
Jelassi S, Brandfonbrener D, Kakade SM, Malach E. Repeat after me: Transformers are better than state space models at copying. arXiv [cs.LG]. 2024. Available: http://arxiv.org/abs/2402.01032
Not surprising at all when you have direct access to a long context. But hey, look at this title.