Установить свойства виджета в 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
#microg Release v0.3.7.250923
https://github.com/microg/GmsCore/releases/tag/v0.3.7.250932
New Features and changes:
Work Profile
You can now sign into various work accounts that setup a work profile when using microG. As microG does not comply with all functionality imposed by organization administrators, you need to enable this feature manually in microG Settings > Work profile. Together with this comes functionality to view and install apps suggested by the organization administrator through the Play Store.
Play Feature Delivery
Apps can request installation of additional languages or features from split packages. You can activate this from microG Settings > Play Store
Face detection
This release ships with initial support for Google's Face Detection API. This functionality is still very incomplete, but works for some apps using it.
Changelog
Maps: Various fixes for HMS Maps (#2737, #2754, #2778, #2825). Thanks @DaVinci9196.
Vision: Improve Barcode Scanning APIs (#2735, #2787). Thanks @DaVinci9196.
Vision: Add initial support for face detection API (#2793). Thanks @DaVinci9196.
Location: Add support for moving WiFis in Eurostar trains (#2821). Thanks @TimoWilken.
Fitness: Add dummy for Recording API (#2760). Thanks @DaVinci9196.
Auth: Various fixes for quick login and third-party Google sign-in (#2660, #2698, #2798). Thanks @DaVinci9196.
Auth: Add support for work accounts (#2553). Thanks @fynngodau.
DroidGuard: Disable access to hardware attestation.
Vending: Fix handling of IAP for multi-account setups (#2681). Thanks @DaVinci9196.
Vending: Add work app store (#2553). Thanks @fynngodau.
Vending: Disable access to hardware keys for play integrity (#2740). Thanks @DaVinci9196
Vending: Add dummys (#2759, #2791). Thanks @DaVinci9196.
Various fixes to improve support for Google Apps (#2652, #2654, #2684, #2738, #2767, #2779, #2780). Thanks @DaVinci9196.
Various fixes for dynamic links (#2662), Fido (#2811), SmsRetriever API (#2786), AppSet dummy (#2781), web view handling (#2836, #2862). Thanks @DaVinci9196, @ale5000-git.
Version bumps (#2813, #2829). Thanks @DaVinci9196, @ale5000-git
String and location infrastructure fixes (#2693, #2755, #2781). Thanks @lucasmz-dev, @Fs00.
New/Updated translations
FakeGAppsmicroG InstallerStableRelease(v1.6)
* Updated #microG to v0.3.2.240913
* Fixed Google Maps crash
* Fixed location settings crash
* Uninstaller is now available
* See latest microG setup here.
🏆 Thanks for @nift4 for UnifiedNLP overlay.
✅ Get it from https://fakegapps.github.io
💬 Join us @FakeGAppsChat
#microg v0.2.28.231657
https://github.com/microg/GmsCore/releases/tag/v0.2.28.231657
Changelog
Entirely new, rewritten location stack
Major update to maps implementation. Thanks fynngodau
Support for reCAPTCHA Enterprise API
Various compatibility improvements
Notes
The new location stack does not support UnifiedNlp modules anymore. This was a step necessary to take to get locations properly working on latest Android versions. This means that some features previously available through UnifiedNlp modules do no longer exist. The goal is to merge the most important of those features into GmsCore. For now, the new locations stack is relying exclusively on Mozilla Location Service for network based location.
microG GmsCore now requests a few additional privileged permissions. As always, privileged permissions are optional for microG and you can continue using microG as an unprivileged app with only minor downsides. The new privileged permissions are:
android.permission.LOCATION_HARDWARE
android.permission.MODIFY_PHONE_STATE
android.permission.NETWORK_SCAN
android.permission.UPDATE_DEVICE_STATS
android.permission.WATCH_APPOPS
Be careful for #MicroG users: Current version is NOT secure for login with your Google Account. It will show your email/password in cleartext in logcat.
It doesn't matter if you have root or not, you only need logcat access to exploit it.
Check the issue here
https://github.com/microg/GmsCore/issues/1567