Установить свойства виджета в 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
🌍 Earth’s gravity is just strong enough to keep an atmosphere and liquid water, but not so strong that gases like hydrogen escape quickly. This balance is rare among rocky planets in our Solar System. ✨
#earth⚡#planet⚡#gravity⚡#geography⚡#nature
👉subscribe Amazing Geography
👉more Channels
🌎 The Great Attractor is a mysterious gravitational anomaly in the universe, pulling our Milky Way and thousands of galaxies towards it at over 600 kilometers per second. This region lies about 150 million light-years away in the direction of the constellation Centaurus, but it is largely hidden by the dense dust and stars of our own galaxy, making its true nature still unknown. ✨
#space⚡#astronomy⚡#gravity
👉subscribe Interesting Planet
👉more Channels
🪐 The cosmic microwave background contains a hidden signature called the "Sachs-Wolfe effect," where variations in temperature are linked to the gravitational pull of massive structures like galaxy clusters. This effect, first detected in the 1990s using data from the COBE and WMAP satellites, shows how even the oldest light in the universe was influenced by the invisible gravity of objects such as the Coma Cluster and the Great Attractor, providing a glimpse into how matter was distributed across the cosmos more than 13 billion years ago. ✨
#cosmology⚡#gravity⚡#universe⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the galaxy cluster known as the Bullet Cluster (1E 0657-56), a cosmic collision has split ordinary matter—seen as hot X-ray gas—from invisible dark matter, which can only be traced by its gravity. By observing how light from background galaxies bends around the Bullet Cluster, astronomers have created detailed maps showing where dark matter gathers, making this system a real, visual proof that most of the universe’s mass is hidden and does not emit light. ✨
#darkmatter⚡#galaxies⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Astronomers have measured that the Coma Cluster—a giant gathering of thousands of galaxies—stays held together by vast amounts of dark matter, an invisible substance that can't be seen but adds enough gravity to keep the cluster from flying apart. Despite all the stars and gas we observe, dark matter in the Coma Cluster outweighs everything visible by more than five times, showing how this hidden ingredient shapes the largest structures in the universe. ✨
#darkmatter⚡#galaxies⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The spiral galaxy NGC 3198 has helped scientists map the mysterious effects of dark matter—a hidden substance that doesn't emit light, but has enough gravity to control how stars move far from the galaxy's center. By tracing the speeds of stars in NGC 3198’s outer edges, astronomers found they move much faster than visible matter alone can explain, revealing an invisible halo of dark matter wrapped around the galaxy. ✨
#darkmatter⚡#galaxies⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The supermassive black hole at the center of the Milky Way, Sagittarius A*, was observed by the GRAVITY instrument on the Very Large Telescope in 2018, revealing that blobs of hot gas orbit just outside its event horizon at about 30% the speed of light. This close-up look confirmed extreme gravity effects predicted by Einstein, and for the first time, scientists watched matter whip around a black hole in real time just kilometers from the point of no return. ✨
#blackholes⚡#gravity⚡#milkyway⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Astronomers have observed an unusual form of space-time distortion called "frame dragging" around the rapidly spinning black hole in the galaxy XTE J1550–564. Frame dragging is an effect predicted by Einstein’s relativity, where a rotating massive object actually twists nearby space and time, causing the orbits of matter and light around it to precess—showing in real life how intense gravity can physically drag space itself into motion. ✨
#wormholes⚡#spacetime⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2015, astronomers using the Hubble Space Telescope watched star light from behind the galaxy cluster Abell 3827 bend and split as it passed through the cluster, a real-life effect of space-time distortion called gravitational lensing. Gravity from massive clusters like Abell 3827 warps the space around them, so light takes curved paths and can appear as multiple, stretched images—direct evidence that space itself can be bent by gravity’s pull. ✨
#wormholes⚡#spacetime⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 On Jupiter, time actually ticks a little faster than on Earth! Because Jupiter is much less dense and has weaker gravity at its cloud tops, its gravitational pull slows time down less than Earth's gravity does—a real effect called gravitational time dilation, where clocks in stronger gravity run slower compared to those farther away from massive objects. ✨
#timedilation⚡#jupiter⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries