Установить свойства виджета в 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
🍿 Bill Skarsgård Rises from the Dead in Robert Eggers' 'Nosferatu'
📆Premiere: December 25, 2024
🎭Genre: #Horror · #Gothic
🎬 The highly anticipated remake of 'Nosferatu' directed by Robert Eggers finally unveils its first trailer, promising a terrifying and dark experience. Bill Skarsgård, famous for 'It', completely transforms into Count Orlok, a vampire who haunts a tormented young woman played by Lily-Rose Depp. The director of 'The Lighthouse' and 'The Northman' surprises us once again with his unique gothic vision, using 2,000 real rats in one scene. With a stellar cast that includes Nicholas Hoult and Willem Dafoe, this version promises to redefine classic horror with a modern and chilling twist. 🎥🦇
📖Title : Conjure Wife
✍️Author : Fritz Leiber
⭐️Rating : 3.80/5 (Goodreads)
📆Published : Apr 1, 1943
————————————————
Summary:In Conjure Wife by Fritz Leiber, Norman Saylor, a rational-minded sociology professor, is shocked to learn that his wife, Tansy, has been secretly practicing witchcraft to protect him from harm and academic sabotage. Believing it's mere superstition, he convinces her to stop. However, as soon as she does, Norman's life begins to unravel—he faces inexplicable misfortunes and threats from unseen forces. Realizing too late that the magical protections were real, Norman must confront a hidden world of witchcraft and rival sorcery. The novel explores themes of gender, power, and the clash between rationalism and the supernatural in modern society.
————————————————
#horror#fantasy#fiction#wicthes#gothic@Bookslibraryofficial@free_novellas
📖Title : Blackthorn
✍️Author : J.T. Geissinger
⭐️Rating : 4.03/5 (Goodreads)
📆Published : Nov 04, 2025
————————————————
Summary:Blackthorn follows Maven Blackthorn as she returns to her haunted hometown after her grandmother’s funeral—only to discover the body has mysteriously vanished. Caught in a generations-old feud between the Blackthorns and the powerful Croft family, Maven is forced to confront Ronan Croft, her first love and the son of her mother’s suspected killer. Their dangerous chemistry resurfaces as whispers of occult rituals, buried secrets, and horrific betrayals emerge. As Maven digs deeper, she uncovers a terrifying truth that threatens everyone she loves. In a town where the dead refuse to rest, love becomes both a weapon and a deadly curse.
————————————————
#romance#gothic#romantasy#fantasy#paranormal@Bookslibraryofficial@free_novellas@eternalmantra
Моё первое творческое видео
❤️
Изначально хотела сделать что-нибудь миленькое про эльфов, но наткнулась на красивую мрачную картинку и понеслось...
Как вам?
Сценарий и картинки: ChatGPT
Анимация/монтаж: Kling, Runway, Luma, CapCut
#aivideo#kling#runway#luma#chatgpt#gothic