Установить свойства виджета в 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
#lua
99 is an alpha Neovim plugin for skilled coders that streamlines AI requests using OpenCode. Install via Lazy with the given Lua config, set keymaps like `<leader>9f` to fill functions, `<leader>9v` for visual AI edits (visual mode only), and `@` for cmp skill autocompletion from custom SKILL.md rules or AGENT.md files. View logs with `:lua require("99").view_logs()`. It boosts your workflow by keeping AI help inside Neovim for fast, restricted code generation without leaving your editor.
https://github.com/ThePrimeagen/99
#lua
OTClient Redemption is a flexible and complete alternative client for the game Tibia, designed to work with OTServ servers. It uses LUA scripting and CSS-like syntax for easy customization of the game interface, allowing you to create new mods and extend features. Written in modern C++20, it supports advanced graphics, sound, multi-language, and mobile platforms through OpenGL. It offers many features like shaders, animated textures, transparency, and an in-game LUA terminal. This client improves performance with multi-threading and garbage collection, and adapts smoothly to server latency for better gameplay. You benefit by having a customizable, high-performance client that enhances your Tibia experience and supports modding and mobile use.
https://github.com/mehah/otclient
#lua
Path of Building 2 is a free offline tool for planning your Path of Exile 2 character builds. It helps you calculate your damage, defenses, life, mana, and other stats accurately by including buffs, auras, and enemy resistances. You can plan your passive skill tree, add and toggle skills, and manage items by importing them directly or crafting custom gear. It supports minions, party play, and sharing builds with others. This tool saves you time and effort by showing exactly how changes affect your character, helping you create strong, optimized builds before playing. It updates automatically and works offline for convenience.
https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2
#lua#github#neovim
Octo.nvim lets you edit and review GitHub issues, pull requests, and discussions right in Neovim. Just open with commands like `//github.com/user/repo/issues/1` or `w` to sync changes instantly. Add reactions, labels, assignees, or reviewers easily. This saves time by keeping all GitHub work in your editor—no browser switching—boosting productivity for developers managing repos.
https://github.com/pwntester/octo.nvim