Установить свойства виджета в 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
#html
The Agent Development Kit (ADK) is an open-source toolkit that helps you build, test, and deploy advanced AI agents easily. It lets you create flexible, multi-agent systems using Python or Java, supports many AI models, and works with different deployment options. ADK offers a rich set of tools, built-in monitoring, and simple integration with Google services, making it easier to develop, debug, and scale your AI applications. This means you can focus on creating smart, efficient agents without worrying about complex setup or compatibility issues.
https://github.com/google/adk-docs
#html
You get access to a huge, well-organized collection of 2,053 ready-to-use n8n automation workflows covering 365 different services, all searchable instantly with a super fast, mobile-friendly documentation system. This system offers lightning-fast full-text search, smart categorization by service and use case, and clear, meaningful workflow names, making it easy to find exactly what you need. You can run the documentation locally with simple setup steps, explore workflows by category or complexity, and even download or visualize them. This saves you time and effort in building automations, helps you discover proven workflows quickly, and supports efficient workflow management and customization.
https://github.com/Zie619/n8n-workflows
#html
The International Obfuscated C Code Contest (IOCCC) is a programming contest where participants write the most confusing and hard-to-understand C code, often under 512 bytes. It started in 1984 to highlight bad coding styles and show how poor structure can ruin a program. The contest uses satire to teach programmers about C’s tricky parts and the importance of clear coding by showing what not to do. Winning entries are both educational and entertaining, helping you learn subtle C language details while having fun. The contest encourages you to explore and understand complex code, improving your programming skills and appreciation for good style.
https://github.com/ioccc-src/winner
#html
You can easily create a secure Octra blockchain wallet by running a simple webserver on your computer. Just clone the wallet generator from GitHub, start the server, and open your browser to generate a new wallet. The tool shows your mnemonic phrase, private and public keys, and address, lets you test signatures, derive addresses for different networks, and automatically saves your wallet file. This helps you safely manage your Octra blockchain assets with full control over your keys and easy access to wallet features without needing complex setups. It’s a user-friendly way to secure and use your Octra wallet locally.
https://github.com/octra-labs/wallet-gen
#html
"开往 Travellings" is a project that helps unknown websites get more visitors. It does this by creating a network where users can click a button to randomly visit other participating sites. This project started in 2020 and aims to make the internet more diverse and open. By joining, users can discover new sites and help smaller websites grow. It benefits users by introducing them to new content and supporting lesser-known creators.
https://github.com/travellings-link/travellings
Is Skia the works-everywhere feature-rich text rendering engine I’ve always been looking for? It seems to work on all sorts of platforms, even on #HTML Canvas with WebAssembly (!)
It even used to have particles support, but was sadly removed from 2 months ago.
https://skia.org/
🐘
Frontend
2-dars. HTML asoslari(davomi)
-Formalar bilan ishlash
-Table bilan ishlash
-Layout va semantik taglar
Mentor : Mahammadamin Abbosov
#frontend#html
👉Telegram | Instagram | YouTobe