Установить свойства виджета в 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
烏克蘭人面對困境,都不忘支持香港人!
佢寄語香港人要奮戰到底,終有一日可將中國驅逐出香港!"Hong Kong is not China in the same way that Ukraine is not Russia. It never has been. We will fight until the last man.", says the director of the Association of Ukrainians in Great Britain.
Despite the toughest moment of Ukrainian, they still stand with Hongkongers.
He told us, we shall keep fighting, China must then be expelled from Hong Kong one day.
#StandwithUkraine#StandwithHongkong
@UkrClubDniproMcr
UN Alarm: Hong Kong's Freedoms Under Severe Threat
UN Chief Guterres' report reveals:
• Activist Chow Hang-tung arbitrarily arrested
• Threats of criminal charges for discussing ongoing cases
• Death threats against Jimmy Lai's family and lawyers
Key concerns:
- Potential criminal liability for UN cooperation
- Attacks on legal representation
"We won't be silenced," says Sebastian Lai, Jimmy's son.
UN Human Rights Council to discuss during 57th session (Sept-Oct 2023).
World's response crucial as Hong Kong's autonomy erodes.
#StandWithHongKong#PressFreedom#UNReport
The HKDM team wish everyone a happy new year! We wish that all of us will continue fighting until our Hong Kong is back!
#fightforfreedom#standwithhongkong#HKDMovement
Due to China's increasing influence and the implementation of a new national security law, Hong Kong's economic position has been severely shaken. The erosion of the city's autonomy and the tightening grip of Chinese authorities have raised concerns among international businesses, leading to a decline in investments and a loss of confidence in Hong Kong as a global financial center. This, coupled with the redirection of cargo and the restructuring of shipping routes, has further diminished Hong Kong's economic prospects.
https://www.rfa.org/cantonese/news/hk-link-04042024161154.html
#ChinaInfiltration#NSL#freeHK#standwithhongkong
Wish everyone a happy Lunar New Year! Bring glory back to Hong Kong in the year of dragon!
#HKDMovement
#glorytoHongKong
#lunarnewyear
#standwithhongkong
監獄規則修訂 引發強烈憂慮
香港政府最新修訂《監獄規則》,容許懲教署以「維護國安」為由,限制律師、宗教人員與在囚人士接觸,立即生效,卻延至 7 月 23 日才提交立法會審議。
此舉可能完全封鎖數以千計的政治犯與外界聯繫。外界無從得知港府在囚室內的行為,尤其中懲教機構推行「思想重整」計劃,更有年輕囚犯曾透露遭受性侵犯。
這不是安全措施,是孤立、是剝奪。
Prison Rule Changes in Hong Kong Spark Alarm
The Hong Kong government’s new amendments to prison rules now permit correctional authorities to restrict inmate access to lawyers and religious staff for “national security” reasons. Though enacted on July 18, the changes won’t face legislative review until July 23.
This effectively blocks thousands of political prisoners from contacting the outside world. The public may never know what happens behind prison walls—especially as reports emerge of indoctrination programs and teenage inmates alleging sexual abuse.
This isn’t about security. It’s isolation, erasure, and silencing.
#silencingHongKong#NSL#PoliticalPrisonersHK#StandWithHongKong
《Harbour of Freedom First Issue》 Excerpt
Race to Campaigns overseas in Aug-Sep
Please download the full version of the first issue on Google drive
PDF(CN):
https://drive.google.com/file/d/1Vms9WnuNSoJtPOLOxf32ONYYZCKo6ULL/view?usp=sharing
PDF(ENG):
https://drive.google.com/file/d/1Qya_BexfjcfehxghTLVOpXteuXVwA-w-/view?usp=sharing
#國際戰線#HongKong#StandwithHongKong
#香港#抗爭#反送中
Tse Wai-chun’s Parting Shot: Too Little, Too Late,
In a jaw-dropping farewell speech, pro-#Beijing lawmaker Tse Wai-chun compared #HongKong’s 1997 handover to the Soviet Iron Curtain, the Khmer Rouge massacres, and #Nazi concentration camps.
He didn’t stop there. Tse mocked “panda tours” and “red tourism” as “neither authentic, nor unique,” and bizarrely called for “colonial tourism,” insisting even tea stains on old Yixing teapots should be preserved.
But let’s not be fooled. For years, Tse voted in lockstep with Beijing’s agenda, opposing the will of #Hongkongers. From suppressing democratic reforms to backing draconian laws, his record is clear. Now, as rumors swirl that he’s been cast aside by the very establishment he served, he suddenly speaks out?
This isn’t courage. It’s convenience.
Tse’s last-minute theatrics don’t erase years of complicity. Hongkongers deserve leaders who stand with them when it matters—not just when the political winds shift.
#FreeHK#StandWithHongKong