Установить свойства виджета в 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
#Notification#Howard_Wu
模块:io.github.howard20181.notificationiconfix
简介:Notification Icon Fix / 通知图标修复
版本:103-1.7.1
更新时间:2026/03/23 00:03:03
更新日志:
变更日志
重构图标生成算法,现在背景是渐变色的也可以计算轮廓
支持 API 101
Changelog
Refactored icon generation algorithm; now it can calculate outlines even with gradient backgrounds.
Added support for API 101.
Fix #1,#12,#13
@lsposed_Modules_Updates_Trackers | @lsposed_Geeks_Bot
#异常通知
我们监控到 洛杉矶2节点出现故障,目前我们正在联系上游询问具体原因,请大家耐心等待。
给您带来不便深表歉意,如有其他疑问请提交服务单联系我们。
#Notification of Anomaly
We have detected a malfunction at the Los Angeles2 node. We are currently contacting upstream suppliers to inquire about the specific cause. Please be patient.
We sincerely apologize for any inconvenience this may cause. If you have any further questions, please submit a service request to contact us.
#异常通知
我们监控到 United Kingdom 区域的1台节点 (Node: GBC) 出现 内存故障,导致内核崩溃一直重启,我们已重新部署新的实例节点,将逐步迁移受影响的实例到同区域新的实例节点上,迁移之间您的实例将会有短暂的失联状态,迁移花费时长将和您的实例磁盘大小有关系,请大家耐心等待。
给您带来不便深表歉意,如有其他疑问请提交服务单联系我们。
#Notification of Anomaly
We have detected a memory failure on one node (Node: GBC) within the United Kingdom region, resulting in a kernel crash and continuous reboots. We have redeployed a new instance node and will progressively migrate affected instances to this new node within the same region. During migration, your instances may experience brief periods of unavailability. The duration of migration will depend on the disk size of your instance. We kindly request your patience during this process.
We sincerely apologise for any inconvenience caused. Should you have further queries, please submit a support ticket to contact us.
#异常通知
我们检测发现我们的SGS区域由于我们和上游的备份BGP Session没有生效,导致上游在维护时和上游的BGP Session断开,目前正在修复,带来不便深表歉意,请耐心等待。
#Notification of Anomaly
We have discovered that our SGS region experienced a disconnection during upstream maintenance due to the failure of our backup BGP Session with the upstreams. We are currently working on fixing this issue and sincerely apologize for any inconvenience caused. Please be patient.
#异常通知
我们监控到 Germany 区域的1台节点 出现 硬件故障,上游正在安排远程手进行查看,请大家耐心等待。
给您带来不便深表歉意,如有其他疑问请提交服务单联系我们。
#Notification of Anomaly
We have detected a hardware failure on one node in the Germany region. Upstream personnel are arranging for remote assistance. Please wait patiently.
We sincerely apologize for any inconvenience this may cause. For any further questions, please submit a service request to contact us.
#异常通知
我们监控到 Singapore Standard 区域的1台节点 出现 磁盘阵列 故障,读写性能下降,我们将在明后天逐步迁移受影响的实例到同区域的其他节点上,迁移之间您的实例将会有短暂的失联状态,迁移花费时长将和您的实例磁盘大小有关系,请大家耐心等待。
给您带来不便深表歉意,如有其他疑问请提交服务单联系我们。
#Notification of Anomaly
We have detected a disk array failure on one node in the Singapore Standard region, resulting in decreased read and write performance. We will be gradually migrating affected instances to other nodes in the same region over the next two days. Your instance will experience a brief period of inaccessibility during the migration. The migration time will depend on the size of your instance's disk. Please be patient.
We sincerely apologize for any inconvenience this may cause. If you have any further questions, please submit a service request to contact us.
#异常通知
我们监控到 盐湖城节点出现故障,目前我们正在联系上游询问具体原因,请大家耐心等待。
给您带来不便深表歉意,如有其他疑问请提交服务单联系我们。
#Notification of Anomaly
We have detected a malfunction at the Salt Lake City node. We are currently contacting upstream suppliers to inquire about the specific cause. Please be patient.
We sincerely apologize for any inconvenience this may cause. If you have any further questions, please submit a service request to contact us.
@shiiinabot
Qué puede hacer este bot?
Un bot para eliminar automáticamente los mensajes no deseados predefinidos del grupo.
Idioma: Portugués
(visto en @BotsGram_cu)
#delete, #group, #notification, #message, #regex, #spam, #picture, #remove
@TodoTask_bot
Qué puede hacer este bot?
Bot simple que ayuda a realizar un seguimiento y te recuerda las tareas pendientes
Idioma: Inglés
(visto en @BotsGram_cu)
#todo, #organize, #productivity, #do, #remind, #alarm, #notification, #notify