Установить свойства виджета в 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
🚀 U.S. President Trump Considers Maritime Blockade Against Iran
On April 12, U.S. President Donald Trump posted on Truth Social about a potential maritime blockade against Iran. According to BlockBeats, Trump suggested this measure if Iran does not make concessions. The statement highlights ongoing tensions between the United States and Iran, with the possibility of escalating actions if diplomatic solutions are not reached.
#Trump#Iran#MaritimeBlockade#USIranTensions#Diplomacy#TruthSocial#TrumpStatement#IranConcessions
🚀 Trump Criticizes Iran's Media Tactics on Truth Social
U.S. President Donald Trump expressed his views on Iran's media strategies on April 11 via Truth Social. According to BlockBeats, Trump stated that Iranians are more adept at handling fake news media and public relations than engaging in warfare. He remarked that Iran seems unaware of its lack of leverage, aside from short-term 'extortion' through international waterways. Trump concluded that Iran's current existence is solely for negotiation purposes.
#Trump#Iran#MediaTactics#FakeNews#PublicRelations#Negotiation#TruthSocial#Extortion#InternationalWaterways
США повышают пошлины на южнокорейские товары 📊
Президент США Дональд Трамп заявил в понедельник, что повышает пошлины на южнокорейские автомобили, пиломатериалы, фармацевтические препараты и другие товары с 15% до 25%. 💸
Основные моменты 📌
Причина: Трамп сослался на то, что Южная Корея не ратифицировала торговое соглашение, которое, по его словам, было заключено с президентом Ли Чжэ Мёном в прошлом году.
Заявление: «Поскольку корейский законодательный орган не ратифицировал наше историческое торговое соглашение, что является его прерогативой, я повышаю южнокорейские ТАРИФЫ на автомобили, пиломатериалы, фармацевтическую продукцию и все другие взаимные ТАРИФЫ с 15% до 25%», — написал Трамп в своём посте в социальной сети Truth Social.
Предыстория: Ранее в этом месяце сообщалось, что Южная Корея будет добиваться льготных условий для снижения тарифов США на импорт микросхем памяти.
🤑Следите за нашими обновлениями, чтобы оставаться в курсе последних изменений в экономике и политике!
#США#ЮжнаяКорея#Пошлины#Трамп#ТорговоеСоглашение#Автомобили#Пиломатериалы#ФармацевтическиеПрепараты#Тарифы#TruthSocial#ЛиЧжэМён#МикросхемыПамяти#Импорт
🚀 Polymarket Predicts Low Probability of Trump Ending Iran Military Action by April 21
The probability of U.S. President Donald Trump announcing the end of military action against Iran by April 21 has significantly decreased to 21%, according to Odaily. This marks a 22% drop in the past 24 hours, with the total trading volume for this event contract nearing $17 million.
The contract stipulates that if President Trump, the U.S. government, or the military officially announces the end of the military action initiated on February 28, 2026, by the specified date (Eastern Time), the market will resolve as 'yes.' Otherwise, it will resolve as 'no.' Valid statements must clearly indicate the end of the action. Informal statements, anonymous sources, or leaked information do not qualify. However, Trump's public written statements, such as posts on his "Truth Social" account, and videos on his social media accounts are considered valid. The primary basis for market resolution is official statements from the U.S. government and/or its representatives, with additional consideration given to consensus from other credible reports.
On the first day of a temporary ceasefire between the U.S. and Iran, Israeli forces launched the largest airstrike against Hezbollah since the conflict began. Iran claimed this violated the ceasefire agreement, leading to the closure of the Strait of Hormuz and threats of deterrent action against Israeli military targets. The White House announced that the first round of U.S.-Iran talks will take place on the 11th in Pakistan. However, Iran stated that three key ceasefire terms have been violated, undermining the "basis for negotiations." Despite this, Iran's Deputy Foreign Minister, Saeed Khatibzadeh, confirmed that the Iranian delegation will attend the talks in Islamabad, Pakistan.
#Polymarket#Trump#Iran#militaryaction#US#ceasefire#Israel#Hezbollah#StraitOfHormuz#WhiteHouse#USIranTalks#Pakistan#SaeedKhatibzadeh#TruthSocial#USGovernment