Установить свойства виджета в 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
#LetHerBloom
#GretaThunberg
❔What happens when a climate activist speaks out on a global conflict?
💬 Greta Thunberg has always been loud - for the planet, and for the people.
However when she spoke up about Palestine, the silence that followed was different…
On June 9, she boarded humanitarian flotilla the Madleen, planning to deliver aid to Gaza. Israeli forces intercepted the vessel in international waters, detaining and then deporting her by June 10 - after being held in an undisclosed location and pressured to sign documents admitting illegal entry.
‼️ She is back safe, but the reality remains:
Solidarity can come with heavy costs.
🌸 At Bloom, we believe speaking up and fighting is better than staying silent!
So let’s fight for justice and stop traditions of staying silent in unfair situations.
And again,
Let Her Bloom!
Greta Thunberg talks about her life
Staying grounded makes coming back to normal life easier, climate activist Greta Thunberg says, as she talks about her handling of fame.
#News#Reuters#GretaThunberg#lifestyle
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Some snippets from Greta’s interview after being deported by Israeli authorities. Continue fighting for Palestinians in Gaza, including those in wider Palestine who are unlawfully imprisoned, including over 400 children.
#Madleen#IOF#GretaThunberg#FreedomFlotilla
https://x.com/SavinoBalzano/status/1974887738919772654
Penso davvero che #AntonioTajani rappresenti uno dei punti più bassi della storia della diplomazia italiana.
Uno che va in televisione a dire che il diritto internazionale conta fino a un certo punto. Uno che parla di “abordaggi pacifici”. Uno che sottolinea come i nostri concittadini non siano stati trattati da #Israele come terroristi.
A parte il fatto che mente spudoratamente: da quanto emerge, le condizioni di detenzione sono state inaccettabili e, soprattutto, gli israeliani si sono accaniti sulle persone trattenute con azioni a dir poco intollerabili. Vale però la pena ricordare, ancora una volta, che i membri della #Flottilla non stavano commettendo alcuna azione illegale. Erano in acque internazionali (acque di tutti e di nessuno) e, soprattutto, del tutto disarmati. Per quanto ci riguarda, i nostri concittadini erano anche su imbarcazioni battenti bandiera italiana, dunque su territorio della Repubblica. La stessa Repubblica di cui, purtroppo (per quanto mi riguarda), #Tajani è ministro.
Ora mi rivolgo a tutti, anche agli amici di destra. Gli attivisti possono anche esservi antipatici (personalmente non ho mai nutrito alcuna simpatia per #GretaThunberg), ma non comprendere che tenere la gente in carcere illegalmente, affamarla e assetarla, costringerla a baciare la bandiera israeliana in una cella infestata dalle cimici, sia semplicemente barbaro, vi rende peggiori di chi più vi ripugna. Sia chiaro.
E qualcuno ha ancora il coraggio di parlare dell’unica democrazia del Medio Oriente? Ma con che faccia?
#BattitoriLiberi: dal lunedì al venerdì alle 17, su Radio Cusano
Greta grooves at Stockholm climate concert
Swedish climate activist Greta Thunberg surprised the crowd at the Climate Live concert in Stockholm by delivering a dance rather than a speech.
#News#Reuters#GretaThunberg#Stockholm#RickAstley
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
https://x.com/SavinoBalzano/status/1974887738919772654
Penso davvero che #AntonioTajani rappresenti uno dei punti più bassi della storia della diplomazia italiana.
Uno che va in televisione a dire che il diritto internazionale conta fino a un certo punto. Uno che parla di “abordaggi pacifici”. Uno che sottolinea come i nostri concittadini non siano stati trattati da #Israele come terroristi.
A parte il fatto che mente spudoratamente: da quanto emerge, le condizioni di detenzione sono state inaccettabili e, soprattutto, gli israeliani si sono accaniti sulle persone trattenute con azioni a dir poco intollerabili. Vale però la pena ricordare, ancora una volta, che i membri della #Flottilla non stavano commettendo alcuna azione illegale. Erano in acque internazionali (acque di tutti e di nessuno) e, soprattutto, del tutto disarmati. Per quanto ci riguarda, i nostri concittadini erano anche su imbarcazioni battenti bandiera italiana, dunque su territorio della Repubblica. La stessa Repubblica di cui, purtroppo (per quanto mi riguarda), #Tajani è ministro.
Ora mi rivolgo a tutti, anche agli amici di destra. Gli attivisti possono anche esservi antipatici (personalmente non ho mai nutrito alcuna simpatia per #GretaThunberg), ma non comprendere che tenere la gente in carcere illegalmente, affamarla e assetarla, costringerla a baciare la bandiera israeliana in una cella infestata dalle cimici, sia semplicemente barbaro, vi rende peggiori di chi più vi ripugna. Sia chiaro.
E qualcuno ha ancora il coraggio di parlare dell’unica democrazia del Medio Oriente? Ma con che faccia?
#BattitoriLiberi: dal lunedì al venerdì alle 17, su Radio Cusano
Thunberg expects 'meaningless' pledges at COP26
For activist Greta Thunberg, success at the upcoming U.N. climate conference would be possible if world leaders honestly admit that their action is not living up to their words.
#GretaThunberg#COP26#UNClimateConference#ClimateChange#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Macklemore endorses the Freedom Flotilla’s ‘Madleen’ on stage, playing a special video that Greta Thunberg recorded from the vessel. Keep all eyes on deck, and all eyes on Palestine.
#GretaThunberg#Macklemore#BreakIsraelsSiege#EndTheBlockade#StandWithGaza#FreePalestine
Listen to some of the Freedom Flotilla Coalition volunteers share why our nonviolent action is critical, just before they boarded the 'Madleen' in Catania. Keep track of our vessel and friends as they sail to Gaza via Marine Traffic or our website. Tag your Foreign Ministries to ensure that they safeguard the 'Madleen', and end their active participation in Israel's genocide and siege of Gaza.
#BreakIsraelsSiege#EndTheBlockade#Madleen#FreedomFlotilla#HuwaidaArraf#GretaThunberg#DrMo#RimaHassan#YasmineAcar#ThiagoAvila