Установить свойства виджета в 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
An #FBI Boston investigation has resulted in charges against 30 individuals for their roles in a global insider trading scheme that netted tens of millions in illicit profits.
The #FBI executed arrests in AL, CA, FL, NJ, and NY today for individuals who are accused of capitalizing on confidential information stolen from leading corporate law firms advising on mergers & acquisitions in Massachusetts and elsewhere.
Two subjects, located in Israel and Russia, are actively being sought.
1:11 PM · May 6, 2026
X LINK
Read more about today's takedown: https://ow.ly/tyCh50YVHRu
Now do CONGRESS...
Excongresista y lobista estadounidense condenado por actuar como agente no registrado de Venezuela en relación con un contrato de 50 millones de dólares.
Un jurado federal en Miami declaró culpable al excongresista estadounidense David Rivera de ejercer presión en secreto en nombre del gobierno venezolano y de lavar millones de dólares vinculados a ese trabajo, en violación de la Ley de Registro de Agentes Extranjeros.
Obtenga más información sobre la investigación realizada por #FBI y nuestros socios encargados de hacer cumplir la ley:
https://www.justice.gov/usao-sdfl/pr/former-us-congressman-and-lobbyist-convicted-acting-unregistered-agents-venezuela
Panic and protests at the #FBI😮
“According to an email from acting Director Brian Driscoll and reviewed by The Gateway Pundit, each field office is required to submit a list of all personnel, current and former, who were involved in January 6th investigations/prosecutions by noon on Tuesday, February 4th.”
Politics, retribution behind FBI purge, agents allege in new lawsuit against Patel, Bondi
Three senior FBI officials who were abruptly fired last month by Kash Patel, the FBI director, are claiming in a new lawsuit against the Trump administration that they were illegally terminated at the direction of the White House for purely political reasons.
The complaint, filed in U.S. District Court in Washington, D.C., Wednesday, alleges Patel told one of the agents that his job as FBI director depended on firing agents involved in past investigations of President Trump.
Patel allegedly said "he had to fire the people his superiors told him to fire, because his ability to keep his own job depended on the removal of the agents who worked on cases involving the President," the lawsuit alleges.
"Patel explained that there was nothing [anyone] could do to stop these or any other firings, because 'the FBI tried to put the President in jail and he hasn't forgotten it,'" the complaint claims. According to the complaint, former FBI agent Brian Driscoll indicated he believed Patel was referring to his superiors at the White House and the Justice Department which "Patel did not deny."
#Trump#FBI
👂More on Trump's Ear ⚠️
🔍🏛️EXCLUSIVE: FBI DIVERTS 25% OF AGENTS TO IMMIGRATION — CHILD CRIMES LEFT UNDERSTAFFED
🔹 Over six thousand FBI agents (quarter of all staff) reassigned to immigration cases in Trump's first 9 months 👮
🔹 Massive 23X increase from previous levels — agents pulled from child exploitation, terrorism, corporate fraud 🚨
🔹 ICE death toll hits 18 in 2026 as Cuban immigrant dies in Georgia detention — suspected suicide 💀
🔹 Federal charges filed against Salvadoran man shot by ICE in California traffic stop gone wrong 🚔
When immigration becomes top priority, who's protecting kids from predators? Priorities matter 🔥⚖️
#Immigration#FBI
@america