Установить свойства виджета в 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
Iqtisodiy terminologiya
📈Fiskal siyosat — bu davlat tomonidan iqtisodiyotni boshqarish uchun davlat xarajatlari va soliq stavkalarini tartibga solish choralaridir.
🏢 Фискальная политика — это совокупность мер, принимаемые государством для регулирования расходов и налогов с целью управления экономикой.
#GraduateSchool#FiscalPolicy#Economy
🔝Web-site |🔝Facebook | 🔝Instagram | 🔝Youtube
📈US Defense Budget and Geopolitical Underpriced Risk
Washington's inability to price the Iran war costs amid a $1.5 trillion military budget push is creating significant fiscal uncertainty for bond and equity markets.
🔗Read Full Analysis
🎯 SPECIAL OFFER: 15% OFF
💸 Coupon Code: salenow15%
🚀 Upgrade to premium signals → https://markets.fxpremiere.com/en/signals?utm_source=telegram
📰 Stay ahead — get breaking financial news & analysis at https://markets.fxpremiere.com/en?utm_source=telegram
#DefenseSpending#FiscalPolicy#TreasuryYields
🚀 U.S. Government Budget Deficit Narrows in March
The U.S. government reported a budget deficit of $164 billion in March. According to Jin10, this figure was slightly higher than the anticipated deficit of $156.7 billion but showed a significant improvement from the previous month's deficit of $308 billion. The narrowing of the deficit indicates a positive shift in the government's fiscal position compared to earlier projections.
#USGovernment#BudgetDeficit#FiscalPolicy#Economy#March2026#GovernmentFinance#EconomicUpdate
🚀 Commodities to Outshine Stocks Amid Geopolitical and Economic Turmoil, Says Bank of America Strategist
Bank of America strategist Michael Hartnett has indicated that investors should pivot towards the commodities market in the coming years, as this asset class is poised to benefit from global geopolitical and macroeconomic instability. According to Jin10, the ongoing Middle East conflicts and the race in artificial intelligence have heightened concerns over supply chains. Governments worldwide are striving to curb the soaring prices of energy and other natural resources, which impact industries and consumers, while also ensuring the supply of critical minerals like rare earths, essential for manufacturing and technology.
Hartnett suggests that for the remainder of this decade, commodities will replace stocks as the primary choice for investors seeking to hedge against risks, inflation, and a weakening dollar. This shift is expected as investors move away from equities in favor of commodities, which are anticipated to become the biggest winners in the "buy anything but bonds" trade. The strategist also notes that excessive fiscal expansion could lead to more frequent bear market rallies in government bonds rather than sustained bull markets.
#Commodities#Stocks#Geopolitics#Macroeconomics#Investment#Inflation#Energy#RareEarths#SupplyChain#AI#FiscalPolicy#MarketTrends
🚀 U.S. March Budget Deficit Estimated at $163 Billion
The U.S. Congressional Budget Office (CBO) has announced that the budget deficit for March is projected to reach $163 billion. According to BlockBeats, this estimate reflects ongoing fiscal challenges faced by the United States. The CBO's report highlights the financial pressures impacting the federal budget, as expenditures continue to outpace revenues. This development underscores the importance of addressing the nation's fiscal policies to manage the growing deficit effectively.
#USBudget#BudgetDeficit#FiscalPolicy#CBO#USFinance#FederalBudget#Economy#MarchDeficit#FinancialReport#USGovernment
Best & Worst Crypto Narratives Revealed
In the last month, AI Agents topped the charts with a 67.02% return, while CEX coins gained 42.61%. On the downside, Modularity fell by 30.99%, Memecoins dropped 28.41%, and LRT decreased by 27.74%. Read more here. ✨ Additionally, Hong Kong lawmakers are considering including Bitcoin in fiscal reserves, aiming to stimulate the crypto industry and boost tax revenue. More details can be found here.
#AI#Crypto#CEX#Bitcoin#Investment#FiscalPolicy#CryptocurrencyIndustry#HongKong#Finance#TaxRevenue#MarketAnalysis#Returns#LawPolicy#AIAgents#Modularity#Memecoins#CryptoTrends#Innovation#Funds#TalentAttraction
#The_Critic🇬🇧📕[PDF]⬇️
#November2025
#Monthly_Magazines
For learning, for free(dom).
@backupofmagazines
This issue dissects Britain’s political fatigue in “Follow the Leader,” charting how #Conservatives lost moral and cultural authority. Essays probe #FiscalPolicy fictions, #CultureWar fatigue, and the right’s need for artistic renewal. Features span #Trump diplomacy, Britain’s agricultural crisis, and a nostalgic defense of #Seapower. In culture, Cézanne’s southern light meets reflections on music, literature, and satire. Critics debate #Opera, #Theatre, #Books, and fine whisky—mixing wit with worry. It’s a portrait of a nation in ideological hangover. #UKPolitics#Brexit#Art#Society#ConservativeCollapse#TheCritic#Philosophy