Установить свойства виджета в 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
MicroStrategy bought another 18,300 $BTC($1.11B) at $60,408 between Aug 6 and Sept 12!
#MicroStrategy currently holds 244,800 $BTC($14.15B), and the average buying price is $38,585.
At current prices, the profit is ~$4.71B!
💰#MicroStrategy has announced an offer of convertible senior bonds maturing in 2032 in the amount of $500 million
The company intends to use the net proceeds from the sale of bonds to purchase additional $BTC and for general corporate purposes.
⚡️ MicroStrategy purchased another $ 14,620BTC for $ 615.7 million at an average price of $42110 per BTC
As of December 26, 2023 — #MicroStrategy stores 189150 BTC purchased for $5.9 billion at an average price of $31,168
Just in: Strategy (prev. #MicroStrategy) has bought 4,225 $BTC for $472.5M at an average price of $111,827 per #Bitcoin
They now hold 601,550 $BTC, bought for a total of approximately $42.87B at an average price of $71,268 per #Bitcoin💰
Strategy (prev. #MicroStrategy) has bought 1,031 $BTC for $76.6M at an average price of $74,326 per #Bitcoin.
They now hold 762,099 $BTC, bought for a total of ~$57.69B at an average price of $75,694 per #Bitcoin.
https://x.com/OnchainLens/status/2036053169927852109
Follow @onchainlens for more onchain updates
Strategy (prev. #MicroStrategy) has bought 22,337 $BTC for $1.57B at an average price of $70,194 per #Bitcoin.
They now hold 761,068 $BTC, bought for a total of ~$57.61B at an average price of $75,696 per #Bitcoin.
https://x.com/OnchainLens/status/2033514795459318052
Follow @onchainlens for more onchain updates
Strategy (prev. #MicroStrategy) has bought 17,994 $BTC for $1.28B at an average price of $70,946 per #Bitcoin.
They now hold 738,731 $BTC, bought for a total of ~$56.04B at an average price of $75,862 per #Bitcoin.
https://x.com/OnchainLens/status/2030978061630603508
Follow @onchainlens for more onchain updates
Strategy (prev. #MicroStrategy) has bought 3,015 $BTC for $204.1M at an average price of $67,700 per #Bitcoin.
They now hold 720,737 $BTC, bought for a total of ~$54.77B at an average price of $75,985 per #Bitcoin.
https://x.com/i/status/2028459100837974064
Follow @onchainlens for more onchain updates
Strategy (prev. #MicroStrategy) has bought 2,486 $BTC for $168.4M at an average price of $67,710 per #Bitcoin.
They now hold 717,131 $BTC, bought for a total of ~$54.52B at an average price of $76,027 per #Bitcoin.
https://x.com/OnchainLens/status/2023746019868160182
Follow @onchainlens for more onchain updates