Установить свойства виджета в 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
🇨🇳 La Chine a procédé au lancement réussi du satellite expérimental Shiyan‑33 qui sera principalement utilisé pour l’étude de l’environnement spatial, a rapporté l’agence Xinhua.
#chine#satellite#lancement
🌍 In 1972, the first Landsat satellite began photographing Earth's surface from space, fueling a new era of digital mapping and revealing real-time changes in forests, cities, and coastlines. ✨
#cartography⚡#satellite⚡#mapping⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The deepest parts of the Amazon rainforest were first mapped by satellite only in the 21st century. Modern exploration now reveals hidden rivers and lost cities from space in this vast green wilderness. ✨
#exploration⚡#rainforest⚡#satellite⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Space-based radar now tracks land subsiding from groundwater loss, revealing areas sinking by centimeters each year. These invisible changes help pinpoint regions at risk of flooding and damage. ✨
#remote⚡#sensing⚡#satellite⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
https://github.com/daleroberts/tv
tv ("#textview") is a small tool to quickly view high-resolution multi-band imagery directly in your terminal. It was designed for working with (very large) #satellite imagery data over a low-bandwidth connection. For example, you can directly visualise a Himawari 8 (11K x 11K pixel) image of the Earth directly from its URL:
It is built upon the wonderful #GDAL library so it is able to load a large variety of image formats (GeoTiff, PNG, Jpeg, NetCDF, ...) and subsample the image as it reads from disk so it can handle very large files quickly. It has the ability to read filenames (or URLs) from stdin and load files directly from URLs without writing locally to disk. Command line options are styled after gdal_translate such as:
-b to specify the bands (and ordering) to use,
-srcwin xoff yoff xsize ysize to view a subset of the image,
-r to specify the subsampling algorithm (nearest, bilinear, cubic, cubicspline, lanczos, average, mode).
$450K Fundraise for Bifrost Connect
OrbitalNerds has raised $450K for its innovative satellite SSH service, Bifrost Connect, on December 4, 2024. For more details, visit OrbitalNerds.
#Funding#Satellite#SSH#BifrostConnect#OrbitalNerds
Myriota Secures $50M Funding
Myriota has successfully raised $50 million in funding for its direct-to-orbit satellite connectivity solutions aimed at the Internet of Things. This funding round took place on December 19, 2024. For more details, visit Myriota.
#Myriota#Funding#Satellite#IoT#Connectivity#SpaceTech#DirectToOrbit#Investment#TechNews#Telecommunications