Установить свойства виджета в 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
#csharp
The Model Context Protocol (MCP) is an open standard that lets AI models connect easily and securely to external data sources and tools, like business systems or cloud services. It acts like a universal adapter, enabling AI to access the right context and data to perform tasks accurately and efficiently. Microsoft offers many MCP servers that link AI with services such as Azure DevOps, SQL databases, Microsoft 365, and more, allowing AI to interact naturally with your data and workflows. This helps you get smarter AI assistance, better automation, and easier integration across your tools.
https://github.com/microsoft/mcp
#csharp
RunCat 365 is a fun and cute app that shows a running cat animation on your Windows taskbar. The cat’s running speed changes based on your computer’s CPU usage, so you can easily see how hard your computer is working just by watching the cat. It’s made for Windows only and is built with C# and .NET 9.0. This app adds a playful and useful visual indicator to your taskbar, making it easier and more enjoyable to monitor your PC’s performance at a glance. It’s free and open-source, with many users enjoying its charm and functionality[4].
https://github.com/Kyome22/RunCat365
#csharp
The eShop reference application is a sample e-commerce website built using .NET 9 and a services-based architecture. It helps developers learn how to create modern web applications. To use it, you need to install .NET 9 SDK, Docker, and possibly Visual Studio or Visual Studio Code. This application is beneficial because it provides a real-world example of how to structure and deploy a complex web application, making it easier for developers to understand and implement similar projects.
https://github.com/dotnet/eShop
#csharp
JSC “KDB Bank Uzbekistan” is looking for Middle or High level of S/W designer with C#, C Programming
Job description:
Software design
· Experience to design new software for multi users using middleware like Apache Kafka
External Interface module development, maintenance and support
· Receiving and analyzing user’s request
· Coding and Test
· Implementation and documentation
· Supporting of the banking system users
Professional requirements:
· Experience of development tool: Visual Studio, GCC or any C compiler
· Experience of Database environment (Oracle)
· At least 2-3 years of experience in the field of programming in C/C++ & C#
· Time management (in order to meet deadlines set by the management)
· English Speaking (should be able to execute instruction and verbal report by English)
· Good written and spoken Russian
Working conditions:
Salary based on interview results, depends on skills and knowledge from 12 mln.soums to 22 mln. soums
Working hours 5/2 from 9:00 - 18:00
Office is located in the center of Tashkent
Benefits:
Medical insurance
Incentive payments for Holidays
Performance bonus
Material assistances for special events (marriage, birth of child and etc.)
Mortgage loan, overdraft facility
Teambuilding
Contacts:
Nozima Yakubova, Head of HR dpt.
telegram: @nozimayakubova
email: [email protected]
More information you can get from our web site: https://kdb.uz/en
#vakansiya#dotnet#csharp
Davr Bank Middle/Senior .NET dasturchi izlamoqda
Talablar:
• C# / .NET Framework
• ASP.NET, REST API
• WCF, Windows services
• Oracle
• JSON/XML
Qo'shimcha ma'lumotlar:
• Maosh - 500$ dan 2000$ gacha
• Ish vaqti - 9:00 dan 18:00 gacha
• Hudud - Toshkent shaxri
Resume yuboring:Nodir
.NET Uzbekistan Community
______
Telegram | Instagram | Youtube
✅ Завтра
Шахматный клиент-сервер на C#. Часть 2. Шахматная доска + фигуры. Unity3D.
📅 28 февраля / 19:00 (время МСК) / онлайн
💵 Бесплатно
📝 Регистрация тут: https://goo.gl/P8dT1K
План вебинара:
~ Вступление. Установка Unity3D.
~ Размещение доски с фигурами.
~ Перемещение мышкой.
~ Фиксация хода.
~ Взятие фигур.
~ Проверка правил.
Для участия в вебинаре обязательна регистрация. На емейл, который вы укажете в регистрационной форме, 28 февраля 2018 года будет отправлено письмо-приглашение со ссылкой на трансляцию.
#Unity3D#Csharp#online#онлайн