Установить свойства виджета в 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
Second US mass shooting in two days kills 4 in Philadelphia
At least four people have been killed and four more wounded in the second mass shooting in as many days in the major northeastern city of Philadelphia amid the epidemic gun violence across the US.
There has been more than 220 mass shooting this year in the US.
#GunViolence
Share and subscribe to American Majority
🚨🔫US GUN VIOLENCE: MASS SHOOTINGS PERSIST DESPITE OVERALL DECLINE
🔹 134 mass shootings through April with 147 killed, 529 wounded nationwide 💀
🔹 Latest incident May 2nd in Amarillo Texas: two dead, ten injured at apartment complex 🏠
🔹 Q1 2026 saw lowest shooting deaths in decade but violence remains daily threat ⚠️
🔹 Mississippi alone reports 116 mass shootings highlighting regional violence patterns 📍
🔹 No single day in Q1 had fewer than 18 shooting deaths across all 50 states 🌍
America's gun crisis continues despite statistical improvements — when will it end? 😔💔
#USNews#GunViolence
@america
Gunman who fired on tourists at Mexican pyramid carried materials related to 1999 Columbine massacre
[Read FullArticle]
@WorldNews#MexicoNews#GunViolence#Columbine
🔫😱 Shocking incident at Jack in the Box in Houston, Texas! 🍔 Former employee opens fire on customer! 🎥 Video shows the terrifying moment it all went down. 😮 Ramos asked for curly fries, but Ford refused. 😡 Verbal argument ensued, captured in 23-minute surveillance footage. 📹 Tensions escalated as Ford grabbed a gun and threw ketchup packets. 🍅 Ramos retaliated, prompting Ford to shoot multiple times. 😨 Thankfully, no one was injured. Ford convicted of assault, probation ended in June. 😤 Stay alert, folks! Danger can lurk anywhere! 🚫💥#Houston#JackintheBox#GunViolence
https://www.foxnews.com/us/video-shows-moment-jack-box-employee-opened-fire-drive-thru-customer-family
Subscribe to @BadVolfNews
💔🚨DEADLIEST US SHOOTING IN 2 YEARS: 8 CHILDREN KILLED IN LOUISIANA TRAGEDY
🔹 Shamar Elkins executed 8 children ages 3-11 in Shreveport — 7 his own kids plus 1 cousin in domestic dispute rampage 😢⚰️
🔹 Children tried escaping through windows, one found dead on roof, another survived jump with injuries — pure horror 🏠💔
🔹 10 total shot including 2 mothers hospitalized, shooter killed by police after carjacking and high-speed chase 🚓💥
America's gun violence epidemic claims more innocent lives. When will enough be enough for our children's safety? 🇺🇸😡🙏
#LouisianaShooting#GunViolence#ChildrenFirst
@america
📉🇺🇸GUN DEATHS DROP 7% IN 2024 — MAJOR IMPROVEMENT FROM 2023
🔹 Total firearm fatalities decreased to 44,447 in 2024, saving 2,281 lives compared to 2023 📊
🔹 Gun homicides reduced 16-27% from 2021 peaks to 15,364 nationwide — 33 states still above 2019 baseline 💀
🔹 Gun suicides reached record high of 27,593 (57% of total) — up nearly 300 from previous year 😔
🔹 Mississippi leads nation at 29.4 deaths per 100k, Massachusetts lowest at 3.7 per 100k 📍
🔹 Police shootings reached 1,210 in 2024 with 95% by firearm — delinquencies remain above pre-pandemic 🚔
First positive trend we've seen in years 🙏✊
#gunviolence#crime#safety#America
@america
🔫🇺🇸GUN VIOLENCE EXPLODES: 65 MASS SHOOTINGS IN JUST 9 DAYS
🔹 Austin deadly shooting: 3 killed, 15 injured on West Sixth Street March 1st 💀
🔹 2,333 homicides already recorded in first quarter of 2026 alone 📊
🔹 130 children (ages 0-11) killed in gun violence this year so far 👶💔
🔹 600 teenagers (12-17) lost their lives to firearms nationwide 🎓😢
🔹 Oakland bar shooting: 2 dead, 5 bystanders wounded in random crossfire 🍸
Cincinnati music venue, Virginia Beach confrontations add to growing toll... 🎵⚰️
California leads with 26 mass shootings since records began — crisis deepens! 📈🏴☠️
#GunViolence#MassShooting#PublicSafety#Austin
@america