Установить свойства виджета в 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
Nod for Vizag Metro hinges on State's financial clearance.
Visakhapatnam district administration seeks ₹600 crore from the State government for private land acquisition under the ₹11,498 crore Metro Rail project
#Infrastructure#Infra
🇮🇷🇺🇸🇮🇱 L’infrastructure pétrolière et gazière iranienne sur les sites de South Pars et d’Assalouyeh a été frappée par les États-Unis et Israël, a rapporté l’agence Tasnim.
#infrastructure#frappe#iran
Fanton EN: Game Unavailability Due to Technical Issues
#infrastructure#Yandex
Fanton EN is currently facing a service disruption due to issues with their infrastructure provider, Yandex. The Yandex team is working to restore the system, and the game will be relaunched as soon as stability is confirmed.
Source: link
@tonlines
🇺🇸🚨BIDEN ANNOUNCES MAJOR INFRASTRUCTURE INVESTMENT
🔹 President unveils $2.1 trillion infrastructure package targeting roads, bridges, and broadband expansion across 50 states 🛣️💰
🔹 Plan includes 500,000 new jobs over next 4 years, focusing on union workers and American-made materials only 👷♂️🇺🇸
🔹 Republicans slam proposal as "reckless spending spree" while Democrats call it "essential for competitiveness" 💸🔥
🔹 Package requires Congressional approval — heated debates expected over tax increases to fund the massive investment 🏛️⚖️
This could reshape America's economy or bankrupt the nation. Which side is right? 🤔💭
#USNews#infrastructure#Biden
@america
👆Cruising down the highway of prosperity!
Experience a remarkable surge in capital expenditure on National Highways, paving the way for a journey towards high growth.
#NationalHighway
#NewIndia
#Infrastructure
Ukrainian Forces Strike Key Russian Oil Infrastructure
On the night of April 7, Ukrainian forces attacked the Ust-Luga Oil terminal in Leningrad region, destroying three Transneft-Baltika tanks. Earlier, on April 5, three RVSN-20000 tanks were damaged at the Primorsk port. Additionally, primary processing units at Lukoil’s refinery in Kstovo were hit. These strikes occurred via Baltic airspace following Moscow’s warnings.
#Russia#Oil#UAF#Infrastructure
The main news of Russia and the world ishere.
Кризис DRAM меняет рынок и подход к обучению современного ИИ.
✔️ Рынок захлестнул дефицит оперативной памяти и других накопителей: ИИ-гиганты выкупили огромные объёмы DRAM, HBM и NAND. Nvidia, по слухам, прекращает поставлять дистрибьюторам видеопамять в комплекте с GPU — теперь её нужно закупать отдельно. На текущий момент цены на SSD и оперативную память выросли на 50-100% по сравнению с началом года. Производители ноутбуков и смартфонов фиксируют задержки поставок, а комплект DDR5 на 64 ГБ уже стоит дороже PS5. 🤯
✔️ Мы спросили Гигачат, как кризис повлияет на развитие нейросетей и обучение моделей. ИИ-помощник формулирует так: "Дефицит памяти — это временный дисбаланс между взрывным ростом ИИ-индустрии и производственными мощностями, которые просто не успели масштабироваться под такой спрос. Высокая стоимость памяти заставляет компании переосмыслить подходы к обучению: вместо наращивания "железа напролом" фокус смещается на эффективные архитектуры и методы.". Подробнее — в видео.
@ai_machinelearning_big_data
#ai#llm#ml#ramcrisis#infrastructure
🌍 In the Alps, some villages rely on cable cars not just for tourists but for everyday transport. Steep slopes and deep valleys make cableways a crucial link for goods and people in remote mountain areas. ✨
#transport⚡#geography⚡#mountains⚡#infrastructure⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
UK Invests Big in AI Development
The UK has announced a substantial investment plan aimed at enhancing its AI capabilities. This initiative, part of a national renewal concept, will focus on developing neural networks for government efficiency, establishing AI growth zones, and bolstering essential infrastructure like data centers and research clusters. More details can be found in the article on ForkLog.
#AI#Investment#UK#Infrastructure#Tech