Установить свойства виджета в 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
#Sweden, national parliament election:
S (S&D) is largest in all constituencies but two in Scania where SD (ECR) leads.
SD, M (EPP), KD (EPP), L (RE) are together stronger in the South.
S, C (RE), V (LEFT), MP (G/EFA) together do best in the North and the three largest cities.
➤ europeelects.eu/sweden
🇸🇪#Sweden: The Swedish Coast Guard has seized a Syrian-flagged vessel named Jin Hui, suspected of being part of Russia’s so-called "shadow fleet".
The ship was sailing in Swedish territorial waters south of Trelleborg and had appeared on multiple sanctions lists. Its destination was unclear. Authorities also suspect the vessel may have been operating under a false flag and was reportedly carrying no cargo.
(via Reuters)
#Sweden🇸🇪
The Luleo Archipelago is a group of Swedish islands in the northern part of the Bayer Belonian, located near the city of Luleo and the mouth of the Lule River.
The sea freezes in January and remains frozen until March - April. Ice roads are cleaned by the four populated islands.
📍Sweden🇸🇪
Gorgeous evening view from the Liseberg amusement park in Sweden. 🎢
Liseberg Amusement Park is also a true symbol of love, as it was built in 1923 by merchant Lamberth for his terminally ill wife Lisa. He transformed the former pastureland into a real garden with trees, flowers, and water areas. 🌳🌺😍
After Lisa's death, the park was donated by her husband to the state, and currently, it attracts about 3 million visitors per year, making it one of the most popular entertainment and leisure destinations in Europe.
#Sweden
@voyage
🇸🇪#Sweden - 🇷🇺#Russia: The Swedish Coast Guard, together with the police, has boarded another vessel suspected of operating under a false flag off the coast of Trelleborg.
The oil tanker, named "Sea Owl I", is believed to be part of Russia's shadow fleet. It was reportedly sailing under an alleged false flag on its way to the port of Primorsk in Russia after departing from Santos, Brazil. Investigators were also alerted by the fact that the ship appeared unusually light and insufficiently loaded.
After the Coast Guard boarded and took control of the vessel, the captain, which is a Russian citizen, was taken in for questioning, however, he has not been arrested yet. Meanwhile, the Russian embassy in Sweden stated earlier today that it is "monitoring the situation", with Russian officials describing the boarding as an act of "piracy".
(via Göteborgs-Posten & Reuters)
🇸🇪#Sweden - 🇷🇺#Russia: Swedish special forces, along with aviation police and the coast guard, have seized a sanctioned Russian vessel which was sailing under a false flag.
The operation took place this Friday while the ship was sailing in Swedish territorial waters in the Baltic Sea near Trelleborg.
The ship was involved in the theft of grain from the territories that Russia has occupied since July 2025.
During last summer, the ship is said to have had its flag changed from a Russian flag to a Guinean flag.
(via Göteborgs-Posten)
🇸🇪#Sweden - 🇷🇺#Russia: The Swedish Coast Guard has boarded the Russian vessel ADLER in the Baltic Sea and carried out inspections on the ship which was reported to regularly transport military cargo to Russian allies in Africa.
The ADLER is operated by M Leasing LLC, a logistics company under EU sanctions and linked to the Russian Ministry of Defence.
The ship was forced to anchor off the Swedish coast yesterday morning after reportedly suffering an engine failure.
According to Swedish media, the crew is cooperating with the Swedish Coast Guard during the inspection.
(via Reuters; 📹 via @wartranslated on X)