Установить свойства виджета в 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
https://code.tutsplus.com/tutorials/10-insanely-useful-django-tips--net-974
10 Insanely Useful #Django Tips
There are quite a few great little tricks and tips one could use on their Django projects that would speed up development and save many headaches in the long run. From basic to obscure, these tips can help any skill-level of programmer become more adept with Django and all it's glory.
1. Use relative paths in the configuration
2. Use the {% url %} tag
3. Use Django admin for your PHP apps
4. Use a separate media server
5. Use the Debugger Toolbar
6. Use Django Unit Testing
7. Use a Cheatsheet
8. Utilize django-chunks
9. Utilize Memcache
10. Stop hacking scripts together and just use Django
https://www.digitalocean.com/community/tutorials/how-to-install-django-and-set-up-a-development-environment-on-ubuntu-16-04
How To Install #Django and Set Up a Development Environment on Ubuntu 16.04
Python/Django stekini o’rganayotgan va kelajakda biror kattaroq loyihani ishlab chiqishda qatnashishni rejalashtirayotganlar uchun juda yaxshi qo’llanma:
Django for Startup Founders: A better software architecture for SaaS startups and consumer apps -
https://alexkrupp.typepad.com/sensemaking/2021/06/django-for-startup-founders-a-better-software-architecture-for-saas-startups-and-consumer-apps.html
Muallif Django orqali quriladigan backend’larning arxitekturasini deyarli hamma tomonini yoritgan: kodni oson bo’lishi, xavfsizlik, test yozish va hokazo. Ba’zi maslahatlariga qo’shilmasam ham, lekin bu qo’llanma e’tiborga loyiq, deb hisoblayman.
#django
https://www.djangoproject.com/foundation/teams/
Teams
Teams indicate who is actively contributing in certain areas.
Ops team
Releasers
Security team
Technical advisory team
Technical board
Technical team
#django
https://docs.djangoproject.com/en/dev/internals/organization/
Organization of the #Django Project
Principles
Core team
Role
Prerogatives
Membership
Technical board
Role
Prerogatives
Membership
Changing the organization
https://simpleisbetterthancomplex.com/2015/11/23/small-open-source-django-projects-to-get-started.html
Small Open-Source Django Projects to Get Started
Learning #Django and #Python can be very fun. I personally love programming with Python and for the most part, work with the Django framework. But in the beginning some stuff can be confusing, especially if you are coming from a Java or C♯ background, like me.
#django#webDevelopment
🤩
Django Girls es una organización internacional sin ánimo de lucro fundada por dos mujeres polacas, Ola Sitarska y Ola Sendecka, para inspirar a mujeres de todos los orígenes a interesarse en el desarrollo de aplicaciones web.
🔗Enlace al libro
-----
Main channel: @repo_science
Coupons: @freecoupons_reposcience
-----
#Python#django#webDevelopment
🛠
Build Python REST API With Django REST Framework
What You'll Learn
- Students learn about fundamental concepts of building REST APIs
- Students learn about fundamental concepts of Django REST Framework
- Students learn about Token and Session authentication mechanism
- Students learn how to deploy Python REST APIs to Heroku
Skills you will gain
- Students will learn building REST APIs with Django REST Framework (DRF)
- Students learn building Authentication system with Django REST Framework
📆 2022
🔗Link
-----
Main channel:@repo_science
Coupons:@freecoupons_reposcience
-----
#python#django#webDevelopment
🌐
Python Django - The Practical Guide
This course covers:
- Installing Django
- Creating and understanding Django projects
- Understanding URLs, views, requests and responses
- Working with templates and static files like CSS and images
- Working with data and models
- Connecting data with relationships (one-to-many, one-to-one, many-to-many)
- Querying data with Django's powerful model solution
- Adding administration panels to your projects
- Handling user input with forms - manually and with Django's built-in form support
- Advanced features like class-based views (and when to use them)
- Dealing with file uploads and how to serve uploaded files
- Working with sessions
- In-depth deployment instructions and examples
- Different ways of deploying and serving static files and user uploads
- And much more!
⚖️11GB
⏳20h+
🔗Link
-----
Main channel:@repo_science
Coupons:@freecoupons_reposcience
-----
http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/
Modern Django: Part 1: Setting up #Django and #React
This will be a multi part tutorial series on how to create a "Modern" web application or SPA using Django and React.js.