Установить свойства виджета в 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
🪐 The galaxy NGC 2683, sometimes called the "UFO Galaxy," has a dramatic, warped disk that gives it a shape unlike typical spirals. Located about 35 million light-years away in the constellation Lynx, its tilted, edge-on view and slightly twisted arms create the illusion of a flying saucer drifting through space, making it one of the most striking examples of galaxies with unusual forms. ✨
#galaxies⚡#shapes⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy NGC 4710, located about 60 million light-years away in the constellation Coma Berenices, is famous for its strikingly thin, edge-on profile that makes it look more like a cosmic needle than a typical spiral or elliptical galaxy. This unusual "boxy/peanut-shaped" bulge is thought to form when a flat disk of stars buckles and warps over time, creating a rare structure that reveals the hidden dynamics shaping galactic evolution. ✨
#galaxies⚡#shapes⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy UGC 2885, sometimes called "Rubin's Galaxy," sports an unusual appearance with its outsized, sprawling disk—nearly 2.5 times wider than the Milky Way. Its vast, faint spiral arms stretch for over half a million light-years, making it not only one of the largest known spiral galaxies but also a cosmic oddity that challenges ideas about how galaxies can grow and maintain such immense, delicate structures. ✨
#galaxies⚡#mysteries⚡#shapes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The galaxy known as the Cartwheel Galaxy, located about 500 million light-years away in the constellation Sculptor, displays a striking ring-and-spoke structure unlike ordinary spirals or ovals. Its unusual shape was created when a smaller galaxy crashed through its center, sending waves of star formation racing outward and leaving behind bright, circular rings and faint, radial arms—an extraordinary cosmic ripple frozen in space. ✨
#galaxies⚡#shapes⚡#collisions⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy NGC 1427A, found in the Fornax Cluster, looks nothing like a neat spiral or smooth oval—it's shaped like a cosmic boomerang. This odd appearance is the result of NGC 1427A plunging through the dense cluster, which causes its stars and gas to be pulled and stretched, creating a lopsided, arrowhead-like structure as it slowly gets torn apart by gravity. ✨
#galaxies⚡#shapes⚡#mystery⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Not all galaxies fit the classic spiral or oval shapes—take the galaxy LEDA 074886, located about 70 million light-years away, which stunned astronomers with its rare rectangular structure. Unlike the familiar swirls or smooth ellipses, LEDA 074886’s boxy outline is thought to be the result of a merger between two smaller galaxies, sculpting a cosmic shape almost never seen in the universe. ✨
#galaxies⚡#mergers⚡#shapes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy ESO 137-001, streaking through the Norma Cluster about 220 million light-years away, has a spectacular "tadpole" shape with long blue tails streaming out behind it. These tails are made of hot, stripped gas and young stars that formed as the galaxy plunges through the dense cluster, showing how powerful cosmic forces can stretch and reshape galaxies far beyond the classic spirals and ovals. ✨
#galaxies⚡#shapes⚡#cluster⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy known as the Tadpole Galaxy (UGC 10214), about 420 million light-years away in the constellation Draco, is famous for its long, sweeping tail that stretches over 280,000 light-years. This striking "tadpole" shape was created when another galaxy passed close by, pulling out a stream of stars, gas, and dust—a cosmic encounter that gave the Tadpole Galaxy its unforgettable, bizarre silhouette among the galaxies. ✨
#galaxies⚡#shapes⚡#collision⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels