Установить свойства виджета в 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
Политика Белого Дома — Л. Томас Блок
ФРС, торговая политика в Азии и промежуточные выборы
— Конгресс уходит на перерыв в связи с Днем поминовения.
— Пауэлл отправится в Белый дом на заседание во вторник.
— Заседание FOMC приближается 14-15 июня, наиболее вероятным представляется повышение ставки на 50 б.п.
— Байден встречается с лидерами Японии, Индии и Австралии для изучения вопросов торгового партнерства.
— Повлияли ли выборы в Джорджии на роль Трампа в Республиканской партии?
#uspolicy
Полные версии всех исследований доступны по подписке
Политика Белого Дома — Л. Томас Блок
— (❗️) Протокол заседания FOMC будет опубликован в среду в 2:00 (21:00 МСК). Фокус на направлении политики ставок.
— Сенатские слушания по Майклу Барру, который станет последним кандидатом Байдена на пост главы ФРБ.
— Промежуточные выборы: Кандидаты, поддерживаемые Трампом, хорошо выступили на прошлой неделе в PA и NC, но некоторые волнения могут быть замечены на этой неделе в GA, где губернатор Кемп, похоже, одержит победу над кандидатом, поддерживаемым Трампом. Но поддерживаемый Трампом кандидат в Сенат Уокер, похоже, тоже идет к победе.
— Помощь Украине демонстрирует растущий раскол в рядах республиканцев.
#uspolicy
Полная версия данного исследования доступна здесь
🇺🇸U.S. AI Memos Reveal a Quiet Convergence with EU Risk Regulation
Two new AI policy memos issued by the White House—M-25-21 and M-25-22—may read like a manifesto for innovation, acceleration, and barrier removal. But beneath the rhetoric lies a nuanced regulatory shift that echoes the EU’s high-risk AI framework. Memo M-25-21, in particular, introduces risk management provisions for “high-impact” AI use cases—defined broadly and open-endedly across six categories, including civil rights, critical infrastructure, and access to essential services.
This flexible and expansive categorization quietly challenges the narrative that the U.S. is lagging in AI governance. In fact, for those familiar with the EU AI Act’s Annex III, the similarities are striking—and in some areas, the U.S. memo is even stricter. A reminder that real regulation doesn't always come with loud announcements.
#AI#AIGovernance#USPolicy
🇺🇸White House Releases National AI Legislative Framework
The White House published a national AI legislative framework aimed at centralizing regulation and preventing U.S. states from enacting their own AI laws. The initiative follows an executive order signed by President Donald Trump in December, which blocked state-level enforcement, and reflects a light-touch federal approach covering areas from data centers to AI-enabled scams.
The framework outlines six objectives for Congress, including tools for parental control over children’s digital presence, streamlined permitting for data centers, and measures to address AI-related fraud. It also proposes balancing intellectual property rights with the need to train AI systems on real-world data and calls for limits on government influence over content moderation by technology providers.
The administration emphasizes sector-specific regulation instead of a single rule-making authority and seeks to preempt state laws governing AI model development. According to White House officials, the framework is intended to support innovation while addressing safety risks associated with broader AI deployment.
#AIRegulation#USpolicy#AIgovernance#TechLaw#ArtificialIntelligence
🇺🇸California Moves to Tighten AI Standards in State Procurement
California Governor Gavin Newsom signed an executive order to strengthen requirements for AI companies seeking to work with the state. The order directs the development of stricter procurement standards, requiring vendors to demonstrate responsible AI policies and meet privacy and security benchmarks to prevent misuse of their technologies.
The initiative contrasts with recent federal actions rolling back AI-related protections. It also expands the state’s use of generative AI in public services, including tools designed to help residents navigate government programs and benefits based on life events such as employment or starting a business.
#AIRegulation#USpolicy#AIethics#PublicSectorAI#DataProtection
Over the past century, oil has played an outsized role in Venezuela. It is no wonder that the United States, in its neverending regime-change plots, chose to target this crucial sector with crushing sanctions.
Our latest video examines the crude reality of coercive measures against the Venezuelan oil industry.
#Venezuela#Sanctions#USPolicy#VenezuelanOil#OilIndustry
https://youtu.be/lwcB4Z9jwGA
🇺🇸U.S. Department of Labor Launches “Make America AI-Ready” Initiative
The U.S. Department of Labor announced the “Make America AI-Ready” initiative, a free AI literacy course designed to provide workers with foundational AI skills. The program delivers training via text messages, allowing users to complete the course in seven days with daily 10-minute sessions, aiming to ensure accessibility, including for individuals without reliable internet or devices.
Developed in partnership with education technology company Arist, the initiative aligns with the White House’s AI Action Plan and America’s Talent Strategy. The course covers five areas: understanding AI principles, exploring use cases, directing AI through prompts, evaluating outputs, and responsible use. According to officials, the program is intended to prepare workers for an AI-driven economy and expand access to AI-related skills and opportunities.
#AIRegulation#AILiteracy#FutureOfWork#USpolicy#AIgovernance