Установить свойства виджета в 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
🪐 Some of the most unusual stars in the universe are "blue stragglers," like those found in the globular cluster M30. Blue stragglers appear younger and hotter than neighboring stars in their ancient cluster, likely because they formed when two stars merged or stole material from a companion—making them stand out as apparent "youngsters" among a population of stellar elders. ✨
#stars⚡#mergers⚡#clusters⚡#nasa⚡#galaxy⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy cluster Abell 2142, located over 1 billion light-years away, is home to one of the largest shock waves ever spotted in the universe—a cosmic "sound wave" stretching millions of light-years through intergalactic gas. This shock wave, observed in X-ray light, is created as entire clusters of galaxies collide and merge, causing hot gas to ripple and heat up on truly enormous scales. ✨
#phenomena⚡#galaxies⚡#clusters⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The James Webb Space Telescope has detected the earliest-known galaxy cluster, named "El Gordo," not as it appears today but as it looked over 10 billion years ago, still forming in the young universe. Webb’s powerful infrared vision allowed astronomers to spot dozens of galaxies caught in the act of merging, giving us a rare glimpse into how the first massive clusters assembled from smaller groups billions of years before our Milky Way even existed. ✨
#galaxies⚡#clusters⚡#webb⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the southern constellation Norma, the galaxy cluster Abell 3627 glows with "radio relics"—giant arcs of radio emission stretching millions of light-years across space. These relics are formed by shock waves traveling through the cluster’s hot gas, energizing particles to near-light speeds, and producing mysterious, ghostly signals that light up the cosmic web between galaxies. ✨
#phenomena⚡#clusters⚡#radio⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In 2011, researchers using the Chandra X-ray Observatory observed the galaxy cluster Abell 2029, where the massive central galaxy produces a ripple in the hot gas around it—a direct result of gravitational space-time distortion. The giant mass of the galaxy and its dark matter bends and stretches space, allowing astronomers to map how real, invisible warps affect the X-rays we detect, turning clusters like Abell 2029 into natural laboratories for exploring the true shape of space itself. ✨
#wormholes⚡#spacetime⚡#clusters⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the galaxy cluster Abell 1689, astronomers have observed light from distant galaxies being bent and stretched in strange ways—a real effect called "gravitational lensing." This phenomenon is caused when a huge mass, like the dense collection of galaxies in Abell 1689, distorts space-time itself—warping the paths of light and creating the illusion of arcs, rings, or even multiple images of the same object in the sky. ✨
#spacetime⚡#lensing⚡#clusters⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Located in the constellation Centaurus, the galaxy NGC 4696 is surrounded by ghostly, thread-like filaments of cool gas that twist and loop for tens of thousands of light-years. These strange structures glow softly as they snake through the much hotter, X-ray-bright plasma of the galaxy cluster core, and scientists believe they are shaped by magnetic fields and slow, turbulent flows—creating some of the most fantastical patterns seen in the cosmos. ✨
#phenomena⚡#filaments⚡#clusters⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the galaxy cluster Abell 2142, astronomers have observed gigantic, invisible boundaries called "cold fronts"—enormous walls of gas as hot as tens of millions of degrees, yet sharply separated from even hotter regions. These fronts, stretching over hundreds of thousands of light-years, form as entire clusters of galaxies collide, creating strange, ripple-like patterns in the vast cosmic gas and revealing the hidden weather of the universe on unimaginable scales. ✨
#phenomena⚡#clusters⚡#gas⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries