Установить свойства виджета в 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
👆 Propheta living up to its name yet again 🔮
Reached 9th TP in the VIP CLUB channel!
Easy $455 with a 5% entry and a $1000 deposit!
VIPs getting filthy rich by the day ☺️🤑🤑ACCESS TO MANUAL TRADING for 70usdt/month
💸Turn time into cash with Propheta AI Signals: pinpoint entries and exits, AI-powered automation, and perfect Cornix compatibility — your automated win streak! GET THE ACCESS TO AI SIGNALS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#tradingviewindicator#tradingbot#buybtc
👀 Well, would you look at that! 👆
Reached 9th TP in just 1 day in the VIP PRO channel!
You could've earned $639 with a 5% entry and a $1000 deposit!
🤑 All this profit could have been yours! 🔥ACCESS TO MANUAL TRADING for 70usdt/month
💸Turn time into cash with Propheta AI Signals: pinpoint entries and exits, AI-powered automation, and perfect Cornix compatibility — your automated win streak! GET THE ACCESS TO AI SIGNALS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#AItrading#buybtc#tradingbot
Reached 9th TP in the VIP CLUB channel!
With a 5% entry and a $1000 deposit, you could've earned $456!
ACCESS TO MANUAL TRADING for 70usdt/month
👉 OOooh yeah baby! And that's what we do every day! Every day milking those exchanges dry! Waiting for you: t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#tradingbot#cryptobot#passiveincome
👆 Propheta living up to its name yet again 🔮
Reached 9th TP in just 36 minutes in the VIP PRO channel!
$277 in profits with a 5% entry and a $1000 deposit!
That's why we call it the "Money Printer" 💴💷💵ACCESS TO MANUAL TRADING for 70usdt/month
👉 Did you know that our referral partners receive extra discounts, even cumulative with the special offer prices?
START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#buycrypto#tradingbot#AItrader
👆 OMG! Would you look at that 👀
Reached 9th TP in just 9 hours in the VIP PRO channel!
Using a 5% entry you could've earned $401 with a $1000 deposit
Feels good to be a Propheta VIP, man... 🏖ACCESS TO MANUAL TRADING for 70usdt/month
👉 Join us and earn big!
Start here: t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#AItrading#CryptoSignal#tradingbot
👆 Propheta living up to its name yet again 🔮
Reached 9th TP in just 9 hours in the VIP CLUB channel!
That's why we call it the "Money Printer" 💴💷💵ACCESS TO MANUAL TRADING for 70usdt/month
👉 Looking at those reports and can't believe what you're seing?
Go to our reports channel and audit us! @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#tradingbot#indicator#autotrading
👍 This is why we're here!
Reached 9th TP in the VIP HTL channel!
Feels good to be a Propheta VIP, man... 🏖ACCESS TO MANUAL TRADING for 70usdt/month
💸Turn time into cash with Propheta AI Signals: pinpoint entries and exits, AI-powered automation, and perfect Cornix compatibility — your automated win streak! GET THE ACCESS TO AI SIGNALS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#tradingbot#signalchannel#AItrader
👆 OMG! Would you look at that 👀
Reached 9th TP in just 2 hours in the VIP CLUB channel!
Easy $338 with a 5% entry and a $1000 deposit!
ACCESS TO MANUAL TRADING for 70usdt/month
👉 Multiplying deposits every day!
Not convinced? Contact us for a free trial - @propheta_help
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#tradingbot#cryptomarket#cryptocurrency
Oops, we did it again 🤣
Reached 9th TP in just 17 hours in the VIP PRO channel!
Easy $609 with a 5% entry and a $1000 deposit!
VIPs getting filthy rich by the day ☺️🤑🤑ACCESS TO MANUAL TRADING for 70usdt/month
👉 We know how to earn 3-4-5 digit amounts without any deposit, with zero risk! Click the link, then START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptoexchange#ethereum#tradingbot