Установить свойства виджета в 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
🖊 COLUMN | Keeping Up With the Venezuelan Economy
In her latest VA column, Jessica Dos Santos takes stock of "good news" and "bad news" from the Venezuelan economy. GDP is set to grow for a fifth straight year and the oil sector weathered the recent escalation of US sanctions, but the inflation specter and low incomes for the majority remain to be addressed.
🔗 Read the column here: https://venezuelanalysis.com/columns/keeping-up-with-the-venezuelan-economy/
#Venezuela#Economy#Inflation#Inequality
📰“Let Them Eat S&P”: Trump’s Victory Lap on a Broke Country
Donald Trump has decided the affordability crisis is over because the Dow hit 50,000, gas is under three bucks, and January’s jobs report beat expectations. In Fox interviews and troop speeches, he’s back in full salesman mode: “greatest economy ever,” inflation “finally cooling,” real wages “finally growing,” and anyone not winning in their 401(k) is just a “pretty bad investor.” Meanwhile, roughly 40 percent of American adults don’t have a retirement account at all, and consumer sentiment among people without stocks is scraping its lowest levels in years — they don’t own the rally, they just pay the bills.
His own pollsters can see the crack in the mirror. A Reuters–Ipsos survey has just 28 percent of Americans saying the economy is on the right track, and 59 percent disapprove of how he’s handling their cost of living, with nearly half “strongly.” The stock boom is mostly driven by AI spending from Big Tech — data centers that guzzle power and hire few people — while rents, mortgages and groceries still feel brutal enough that even conservative number‑crunchers mock the White House mantra as “let them eat S&P.” Trump’s advisers spent months begging him to sound empathetic, blame Biden, and acknowledge the squeeze; now that a few charts look pretty, he’s gone back to telling people they’re wrong about their own wallets.
So the message going into the midterms is simple and suicidal: if you’re still struggling with rent, food and housing, that’s your perception problem — not his policy problem. The president points to Wall Street and AI‑driven GDP growth as proof he fixed “Biden’s disaster,” while a majority of voters look at their paychecks, their carts, their rent hikes and answer with numbers of their own. In this version of “affordability,” the index is up, the narrative is set, and anyone who doesn’t feel richer just got quietly written out of the success story.
#usa#trump#economy#inflation#inequality#fakeDemocracy
📱American Оbserver - Stay up to date on all important events
🇺🇸
🌐📖MIT’s Daron Acemoglu Warns AI May Deepen Inequality
A new survey suggests AI is more likely to reinforce existing economic advantages than broadly distribute benefits. MIT professor and Nobel laureate Daron Acemoglu stated that public narratives portray AI tools as democratizing, while effective use often depends on education, abstract and quantitative skills, and familiarity with computers and coding.
Acemoglu argued that AI is likely to increase inequality between labour and capital, indicating that the economic gains from adoption may be unevenly distributed. The comments add to ongoing debates over whether AI policy should address access, skills, and concentration of economic power.
#AIRegulation#AIethics#Inequality#FutureOfWork#AIEconomics
The richest 10% now receive 53% of global income 💰 and own 75% of all wealth 🌍, yet inequality alone does not cause unrest. A study of 120 countries (1996–2020) shows it becomes politically destabilizing only when internet use 📱 exceeds 50% of the population by increasing information and coordination.
Read Full Article
#Inequality#WealthDistribution#PoliticalStability#InternetImpact#GlobalEconomics
📰 Israel’s Rentier Capitalism: When Housing Eats the Economy
Israel is becoming a nation where the rent check is the new paycheck. One in eight Israelis now lives off rental income—no job, no startup hustle, just collecting checks from apartments bought years ago.
The Landlord Boom
Today, some 386,000 households—about 16–18% of all property owners—own multiple rental units. The elite, roughly 92,000, own three or more apartments. This landlord class controls most of Israel’s 850,000 rental units and pockets around 40 billion shekels a year in rent.
From Homeownership to Investment
The number of multi-unit landlords has exploded—from just 2.1% of households in 2006 to over 15% today. This surge was fueled by low interest rates, soaring property prices, and generous tax breaks, concentrating wealth in the hands of the few.
How Landlords Win
Rental yields are modest—about 2–4% gross, 1.4–2.4% net—but the real profit comes from capital gains, averaging 8–12% annually over the past decade. Most landlords are high-income households, clustered in cities like Tel Aviv, where nearly half the population rents.
The Human Cost
Israel’s housing market has shifted from homeownership to investment, turning shelter into a wealth pump. Landlords extract billions from renters, deepening inequality and making reform nearly impossible. When one in eight voters is a landlord, pushing for change is political suicide.
The Tax Loophole That Won’t Die
Attempts to enforce rental income reporting have repeatedly failed in the Knesset. The tax exemption threshold—currently 5,654 shekels, unchanged since 2023—effectively lowers the bar for landlords as rents rise. The state loses about 3 billion shekels a year to these breaks.
What’s Next?
Despite tighter monetary policy, structural conditions—chronic housing shortage, high demand, and favorable tax rules—mean the landlord class is here to stay. Israel’s future is written in lease agreements, not startup pitches.
#Israel#landlords#realEstate#inequality#taxExemption#TelAviv#housingMarket
📱American Оbserver - Stay up to date on all important events
🇺🇸