Установить свойства виджета в 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 giant Trilithon stones at Stonehenge in England each weigh about 25 tons and were transported from over 30 kilometers away. These standing stones date to around 2500 BCE and were arranged in a unique horseshoe pattern that still stands today. ✨
#archaeology⚡#megaliths⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 Towering over the Peruvian desert, the megalithic complex of Sacsayhuamán features walls made from stone blocks weighing up to 200 tons each. These blocks fit so precisely that even a piece of paper cannot slide between them. ✨
#archaeology⚡#history⚡#megaliths
👉subscribe Interesting Planet
👉more Channels
🌎 Rising above the Jordanian desert, the prehistoric megaliths known as “desert kites” are vast stone structures with funnel-shaped walls stretching for hundreds of meters. Archaeologists have identified more than 6,000 desert kites across the Middle East, mostly built between 7000 BCE and 2000 BCE, likely used to trap wild animals. ✨
#archaeology⚡#megaliths⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 Looming over the English Channel, the Carnac stones on Guernsey form a megalithic passage grave known as Le Déhus. Built around 3500 BCE, it features a massive stone chamber and carved capstones. The longest stone weighs nearly 10 tons and the site is aligned to the sunrise at midsummer. ✨
#archaeology⚡#megaliths⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 Hidden in the forests of western Russia, the megalithic dolmens of the Caucasus feature massive stone chambers built from precisely carved granite slabs. Some of these structures date back over 5,000 years and weigh more than 15 tons each, puzzling archaeologists with their construction methods and unknown cultural origins. ✨
#megaliths⚡#archaeology⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 Stonehenge in England features massive upright stones called sarsens, each weighing up to 25 tons. Built around 2500 BCE, the monument’s purpose is still debated, but recent studies found the stones were transported from over 25 kilometers away on wooden sledges and rollers. ✨
#archaeology⚡#megaliths⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 The megalithic site of Carnac in Brittany, France, contains over 3,000 standing stones arranged in rows stretching more than 4 kilometers. Erected between 5000 and 3300 BCE, these granite monoliths are among the world’s largest collections of ancient stone alignments. ✨
#archaeology⚡#megaliths⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 In southern England, the ancient monument of Silbury Hill rises 40 meters and was built over 4,000 years ago using chalk and earth. Archaeologists have never found burials, temples, or inscriptions inside, leaving its purpose mysterious. Silbury Hill is the largest man-made prehistoric mound in Europe. ✨
#archaeology⚡#mystery⚡#megaliths
👉subscribe Interesting Planet
👉more Channels
🌎 The “Plain of Jars” in Laos is scattered with thousands of massive stone jars, some weighing over 10 tons. Archaeologists date them to the Iron Age, around 500 BCE to 500 CE, but their purpose—possibly for funerary or storage rites—remains uncertain. Over 90 jar sites have been documented across the region. ✨
#archaeology⚡#megaliths⚡#mystery
👉subscribe Interesting Planet
👉more Channels
🌎 The Baalbek Trilithon in Lebanon features three enormous stone blocks, each weighing around 800 tons, forming the base of the Roman Temple of Jupiter. These stones are among the heaviest ever used in ancient construction, and were quarried and moved more than 800 meters from their original location. ✨
#archaeology⚡#megaliths⚡#engineering
👉subscribe Interesting Planet
👉more Channels
🌎 Towering in the remote Pacific, the moai statues of Easter Island were carved from volcanic rock between 1400–1650 CE. The heaviest moai weighs around 82 tons, showcasing the islanders’ exceptional engineering with limited technology. ✨
#megaliths⚡#archaeology⚡#engineering
👉subscribe Interesting Planet
👉more Channels
🌎 Rising from the Lebanese landscape, the megalithic stones of Baalbek include the Stone of the Pregnant Woman—one of the world’s largest quarried stones at over 1,000 tons. Ancient builders moved and stacked these limestone giants with such precision that modern engineers still debate the techniques used. ✨
#archaeology⚡#megaliths⚡#engineering
👉subscribe Interesting Planet