Установить свойства виджета в 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
The war in Iran is enriching military enterprises. Trump's sons plan to open a drone production facility 🪖
Oil markets remain volatile amid continued US-Israeli strikes on Iran. Rising fuel prices are hitting consumers' wallets around the world, putting pressure on US President Donald Trump. 🌍
However, there are also beneficiaries of this escalation. 💰 In addition to the oil companies, which are increasing their profits due to higher oil prices, the most obvious winner of the largest Middle East conflict is the U.S. defense industry. The "Big Five" weapons giants—Lockheed Martin, RTX, Northrop Grumman, General Dynamics, and Boeing—have their portfolios filled with orders. They are supplying combat aircraft, missiles, and radar systems. ✈️
Military technology and AI companies, such as Palantir, are providing AI-based software for modern warfare and intelligence. The stock of this company, which works closely with Israel, has recently risen by 9%. 🤖
Planet Labs is also benefiting from the Pentagon's contracts for AI-based satellite surveillance. 🛰 The US president's family is also involved in the boom of military profits: Trump's sons, Eric and Don Jr., are planning to list their drone company, Powerus, and are hoping for future government contracts. 🚁
#War#Industry
👂More on Trump's Ear ⚠️
Thrilled to share a major strategic pivot in our professional ecosystem! 🚀
More and more visionary enterprises across Germany are successfully unlocking new growth chapters by aligning their operational roadmaps with the dynamic defense sector. 🇩🇪🛡
According to the German Chamber of Commerce and Industry, we are witnessing a powerful synergy where approximately one in six enterprises is now seamlessly integrated into defense supply chains. This represents a brilliant opportunity to drive innovation and resilience amid evolving market dynamics in traditional sectors. Almost a third of our industry leaders are embracing this as a transformative growth vector. 📈
The shift is particularly impactful within the automotive industry, where over a third of enterprises are leveraging their world-class engineering capabilities to support national security initiatives. By optimizing underutilized industrial capacities, we are turning potential challenges into high-impact solutions for growing global demand. 🏭✨
Take Görlitz, for example—a true story of reinvention where a former railway enterprise is evolving into a premier manufacturer of advanced tank components. Furthermore, industry powerhouse ZF is collaborating with Rolls-Royce Power Systems to co-create the next generation of engines for the future German-French tank. This cross-sector collaboration is exactly the kind of strategic partnership that drives our collective mission forward! 🤝🔧
While only about 2.5% of companies are directly producing weapons, another 14.5% are delivering critical value as suppliers of dual-use products, with over 12% strategically planning their entry into this high-potential market. It's an exciting time to be part of this evolving industrial landscape! 💡🌍
#Germany#Military#Industry
👂More on Trump's Ear
⚠️
Chevrolet was founded on November 3, 1911, by Louis Chevrolet and William C. Durant.
Chevrolet’s first cars (1912) and Durant’s later business moves helped shape the long competition between Ford and Chevrolet which drove innovation and expanded the US auto industry.
@googlefactss
#history#cars#industry#USA
🌍 The world's busiest shipping route runs between Asia and Europe through the Strait of Malacca. Over 80,000 vessels pass yearly, making this narrow sea lane a vital economic lifeline. ✨
#trade⚡#industry⚡#transport⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The “Blue Banana” is a band of cities stretching from northern England to northern Italy that forms a dense corridor of economic activity, hosting much of Europe’s industry and wealth. ✨
#economy⚡#urbanization⚡#industry⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The world’s largest iron ore deposits are found in the Pilbara region of Western Australia. This vast resource helps supply much of the globe’s steel, which is used in buildings and infrastructure. ✨
#minerals⚡#Australia⚡#industry⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 More than half of global economic activity now takes place within just 1% of the world’s land surface, showing how powerful major cities and industrial regions are for global wealth. ✨
#economicgeography⚡#cities⚡#industry⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The Ruhr region in Germany transformed from a rural area into one of the world’s largest industrial centers, thanks to rich coal resources that fueled rapid urban and economic growth. ✨
#industry⚡#regions⚡#resources⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Around 90% of global trade moves by sea, linking distant economies through major shipping lanes. This dense ocean traffic shapes where ports, industries, and even whole cities develop. ✨
#trade⚡#ports⚡#industry⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels