Установить свойства виджета в 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
Раз уж девелоперы OpenAI не спешат с созданием сборника ChatGPT-плагинов — этим занялись любители.
Самодельный список не только вместил все доступные на сегодня ChatGPT-моды, но и полезные руководства с примерами промтов.
Всем поклонникам ChatGPT — сюда.
OpenAI Community | #plugins
Большой набор пресетов для моушн-дизайна в Blender: https://blendermarket.com/products/motion-animate---speed-up-motion-graphics?ref=110
#Blender#Plugins#3D
#other#awesome#chartjs#charts#integrations#plugins#resources
Chart.js is a flexible JavaScript library for creating interactive charts with extensive customization options. You can use it with popular frameworks like React, Vue, and Angular through dedicated adapters, and extend its functionality with plugins for styling, features, and data handling. The library supports three major versions—v2 (April 2016), v3 (April 2021), and v4 (November 2022)—each with different plugin compatibility. This means you can choose the version that best fits your project needs and find compatible extensions for charts, animations, zooming, data labels, and more. Whether you need basic charts or advanced visualizations with custom interactions, Chart.js provides the tools to build professional data displays efficiently.
https://github.com/chartjs/awesome
#cmake#audio#ios#linux#macos#plugins#sdk#vst3#win32
VST 3 is an improved version of the VST audio plug-in interface. It offers several benefits, including better performance by only processing audio when needed, dynamic input/output configurations, and precise automation. Users can also enjoy a more organized interface and support for advanced audio features like 3D sound. These improvements make it easier for developers to create plugins and for users to work with them in digital audio workstations (DAWs), enhancing overall audio production efficiency.
https://github.com/steinbergmedia/vst3sdk
#typescript#ai#anthropic#artifacts#assistant_api#aws#azure#chatgpt#chatgpt_clone#claude#clone#dall_e_3#deepseek#gemini#google#librechat#o1#openai#plugins#vision#webui
LibreChat is a free, open-source AI chatbot platform that lets you use many AI models like OpenAI, Anthropic, and AWS in one place. It offers advanced features such as secure code execution in multiple programming languages, AI assistants that can handle files and tools without coding, and the ability to generate images and diagrams directly in chat. You can search conversations easily, manage multiple chat threads, and customize the interface to fit your needs. LibreChat supports multiple languages, speech input/output, and secure multi-user access. It can be deployed locally or on the cloud, giving you flexibility and control over your AI experience. This means you get a powerful, customizable AI assistant without needing to pay for ChatGPT Plus or rely on a single provider[1][3][5].
https://github.com/danny-avila/LibreChat