Установить свойства виджета в 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
⚡️swap.coffee: Major UI Widget Kit Update
#update#documentation
swap.coffee has introduced a significant update to its UI Widget Kit. The update features a new design, supports MEV Protect, Limit Orders, DCA, and much more. Updated documentation is now available for users at @swapcoffee_dev_chat.
Source: link
@tonlines
Cekura Secures $500K Funding
Cekura has completed a funding round of $500K on December 4, 2024. The company specializes in browser agents that ensure product documentation remains current.
#Cekura#Funding#Documentation#Tech#BrowserAgents#Startup#Investment #2024 #Innovation#Business
Documentation News:
In Moscow, two men who failed to register for military service were stripped of their citizenship
This was reported on the Telegram channel by the official representative of the Russian Ministry of Internal Affairs Irina Volk.
Volk recalled that, in accordance with Russian law, every man with acquired citizenship must register for military service within two weeks. Violators face punishment.
Our advise to members:
1. Comply with local laws. Register for military service if you are of draft age and have acquired citizenship.
2. Similarly, if you are of draft age and have no plans to register for military service, then you should consider not applying for citizenship.
Like the popular saying goes, you can't eat your cake and have it.
https://t.me/nido_russia/1827
#laws#naturaliation#documentation#passport#citizenship
Source: Life(.ru)
#html#documentation#hacktoberfest#hass#hassio#home_assistant#jekyll
You can set up and contribute to the Home Assistant website easily by following the developer documentation, which explains how to edit and preview the site locally using simple commands. This helps you see your changes live on your computer before sharing them. There are also tools to speed up website updates by temporarily hiding blog posts you’re not working on, making the process faster. This setup benefits you by making it straightforward to improve the site, test changes quickly, and manage content efficiently without delays. It’s designed to support smooth collaboration and faster website maintenance.
https://github.com/home-assistant/home-assistant.io
#python#documentation#gotchas#interview_questions#pitfalls#python#python_interview_questions#snippets#wats#wtf
Python is a high-level, easy-to-read programming language widely used in many fields like web development, data science, and AI. The "What the f*ck Python?" project helps you understand tricky, surprising Python behaviors through clear examples and explanations. It reveals lesser-known features and common pitfalls, making it easier to write better code and debug problems. By exploring these examples, you can deepen your knowledge of Python’s internals, improve your coding skills, and avoid common mistakes, which benefits both beginners and experienced programmers alike[3].
https://github.com/satwikkansal/wtfpython
#ruby#api_documentation#app#devdocs#developer_tools#docs#documentation#documentation_tool#hacktoberfest#offline#pwa
DevDocs is a free, fast, and easy-to-use web app that lets you quickly search and browse official API documentation for many programming languages and tools all in one place. It works offline, has a clean interface, supports keyboard shortcuts, dark mode, and mobile use. You can access over 100 documentations like HTML, CSS, JavaScript, and more without switching tabs or searching Google repeatedly. It saves time by providing instant search results and keeps everything organized, making coding and learning more efficient and enjoyable. You can use it online or run it locally with Docker for even faster access[1][2][3][5].
https://github.com/freeCodeCamp/devdocs
— LibreCellular 21.04 documentation –https://librecellular.org/
The LibreCellular project aims to make it easier to create #4G cellular #networks with open source software and low cost software-defined radio (#SDR) hardware. Seeking to achieve this via validated hardware and software configurations that are subjected to rigorous testing, together with additional tooling and #documentation for repeatable deployment.
LibreCellular will build on the work of numerous existing open source software and hardware projects, related to both the #cellular platform itself and associated test #infrastructure. Where necessary additional components will be developed, with any software source code and #hardware designs published under #opensource licences. The focus is very much on integration, testing, packaging and documentation, reusing and building upon existing solutions..
#LibreCellular#CellulaireLibre
#python#ai#ai_agents#ai_coding#claude_code_plugin#claude_code_plugins#claude_code_plugins_marketplace#claude_marketplace#claude_plugin#claude_skills#docs#documentation#mcp#mcp_server#postgres#postgresql#skills
pg-aiguide helps AI coding tools create better PostgreSQL code with semantic search of official docs, best-practice skills for schemas/indexes, and extension info like TimescaleDB. Install it free as a public MCP server or Claude plugin in tools like Cursor/VS Code for one-click setup. It fixes AI's weak spots—outdated code, missing constraints (4x more), indexes (55% more), and modern PG17 features—producing robust, fast, maintainable schemas that save you debugging time and production fixes.
https://github.com/timescale/pg-aiguide
#python#blocknotejs#collaborative#django#documentation#g2g#government#knowledge#knowledge_base#mit#mit_license#opensource#reactjs#realtime_collaboration#self_hosted#wiki#yjs
Docs is a collaborative online text editor that helps you and your team write, edit, and organize documents together in real time, even offline. It offers easy formatting, AI tools like summarizing and rephrasing, and secure sharing with controlled access. You can export documents in various formats and create structured knowledge with subpages. Docs is open source, easy to self-host, and used by public organizations, ensuring your data stays secure and private. This tool saves time, improves teamwork, and turns your notes into organized knowledge you can access anytime. It’s great for teams wanting efficient, secure, and collaborative document editing.
https://github.com/suitenumerique/docs