Установить свойства виджета в 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
To participate in the Olympics, an Australian field hockey player amputated part of a broken finger instead of getting a cast and missing the Games.
#Hockey
👁Subscribe to Main Event | Sport News
"We Lost a Child. The Support of Loved Ones and the Club Saved Us."#Hockey
A Touching Farewell from the Canadian Superstar to Tampa Bay
Steven Stamkos, after 16 years with the Tampa Bay Lightning, is leaving the team. This summer, he entered the free agency market and signed a four-year contract with the Nashville Predators. In a column on The Players' Tribune, the Canadian forward bid farewell to the club and the city where he became a star. Here is the translated material.
This memory has been replaying in my head over the past few days.
7:30 AM. The day after our victory over Montreal, we had won our second Stanley Cup. The entire team was at my place. Parents, kids, partners, friends. No one had slept. We were all exhausted, but it was one of the best nights ever. We sat together, sharing joyful moments. We savored the moment. My son Carter got out of bed. He came down to the kitchen and made himself his favorite cereal for breakfast, only this time, he ate it from the Stanley Cup. I looked at him and thought, "Man, what a special moment this is..."
I will remember this scene forever. Forever.
👁Subscribe to Main Event | Sport News
Hockey player Matthew Tkachuk gave the gold medal to Donald Trump. American hockey players met with President Donald Trump shortly before his address to Congress.
Trump invited the athletes in a telephone conversation, which was organized from the locker room of the Olympic Games by FBI Director Kesh Patel. When Tkachuk handed over the award, Trump joked that he would not give it back. The U.S. national team won Olympic gold in men's hockey for the first time in 46 years. The last time the Americans won was so long ago — in 1980. In the deciding match on Sunday, February 22, 2026, the USA defeated Canada 2-1 in overtime.
#Trump#Hockey
👂More on Trump's Ear ⚠️
The U.S. women's national hockey team refused to go to a meeting with Trump.
The U.S. women's hockey team refused to attend the State of the Union ceremony, President Donald Trump's State of the Union address, NBC reported. 🏒
USA Hockey thanked the president for the invitation and noted that the team appreciates the attention. They won't be able to come because of their studies and work.
The invitation came after Trump's joke. He called the men's team after the victory and said he would invite the women as well. He added that otherwise he could be impeached.
The president's joke was considered inappropriate and downplayed the achievements of the women's national team.
Immediately after the refusal, the national team accepted an invitation from rapper Flavor Flav to host a celebration in Las Vegas.
However, it will be held only at the end of April, when the athletes' playing season ends.
However, conservative media have already written that the hockey players preferred the rapper. 📺
#Trump#Hockey
👂More on Trump's Ear ⚠️
🏒 STANLEY CUP CONFERENCE FINAL
New York Rangers vs Boston Bruins
The road to the Stanley Cup continues.
Two historic franchises face off in one of the biggest matchups of the season. Momentum, pressure, experience, intensity.
Who advances?
Make your prediction now on EdgeMarket:
https://edgemarket.ai/bnb/ice-hockey/new-york-rangers-vs-boston-bruins/statistics/69f1dba4422739f6001fea43
#StanleyCup#NHLPlayoffs#Rangers#Bruins#EdgeMarket#SportsPredictions#AI#Hockey
«Олимпийское панно», digital art, Doping-Pong, 2010-2011 гг. #dopingpong#digitalart#olympics#winterolympics#snowboard#figureskating#skiing#hockey#russiancontemporaryart
📖Title : Merry Little Kissmas
✍️Author : Lauren Blakely
⭐️Rating : 3.90/5 (Goodreads)
📆Published : Oct 28, 2025
————————————————
Summary:In Merry Little Kissmas, a cheerful professional matchmaker takes on what should be an easy holiday job: finding a date for her brother’s grumpy best friend, a single-dad hockey player who hates Christmas. When he bets she can’t do it, she decides to fake-date him herself to prove she can. Set in the snowy small town of Evergreen Falls, their pretend romance includes Christmas competitions, tree farms, hot cocoa, and forced proximity. As playful banter turns into real intimacy, the hero’s guarded past slowly surfaces. By Christmas Eve, both must decide whether their growing feelings are just seasonal magic—or true love.
————————————————
#christmas#holiday#romance#audiobook#hockey#merrylittlekissmas#laurenblakely#sportsromance#contemporary@Bookslibraryofficial@free_novellas@eternalmantra
🎙Повторный выпуск с Марком Барберио!
На этот раз — полностью на его родном английском языке.
Если тебе интересно послушать историю Марка без перевода или ты практикуешь английский — этот выпуск для тебя.
👉 Включай, смотри и прокачивай язык вместе с хоккейной историей.
#PROавтора#podcast#madjozef#hockey#english#Barberio#Severstal#NHL#KHL#спорт#подкасты