Установить свойства виджета в 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
Several countries to import wheat from India after ban on shipment lifted
The agriculture ministry has projected a record 120 MT of wheat output in 2025-2026 crop years (July-June), trade sources said that output is definitely higher than 117 MT in 2024-25 crop year.
The area under wheat this season has increased to 33.41 million hectares (mha), 3% higher than last year, exceeding the normal sown area of 31.2 mha
#Agriculture
https://t.co/uvwNj9BuM7
Job Title: Poultry production manager
Job Type: On-site - Permanent (Full-time)
Job Sector:#Agriculture
Work Location: Gondar, Ethiopia
Experience Level: Senior
Vacancies: 1
Salary/Compensation: Monthly
Deadline: 8/11/2023
Description:
We are looking for a skilled poultry production manager who has at least a Bsc in animal science and related field. The applicant needs to have a minimum 6 years of experience. The location is Weleta.
__________________
Purpose Black Eth Trading s.c
[Verified Company ✅]
128 Jobs Posted
From: @freelance_ethio | @freelanceethbot
For our Amharic Channel, Join @afriworkamharic
🌎 The guano islands of Peru once fueled global agriculture. Thick layers of seabird droppings here created natural fertilizer so valuable, nations fought for control in the 19th century. ✨
#history⚡#ecology⚡#agriculture
👉subscribe Interesting Planet
#Koulouba | 06 mai 2025 | #Agriculture
15e Session du CSA : Priorité à la souveraineté alimentaire et au développement rural
Sous la présidence du Général Assimi GOÏTA, la 15e session du Conseil Supérieur de l’Agriculture (CSA)s’est tenue le 6 mai 2025 à Koulouba, réunissant le Premier ministre, des ministres clés et des représentants agricoles.
À l’ordre du jour :
- Bilan 2024 (inondations, insécurité)
- Exécution des recommandations précédentes
- Perspectives 2025-2027
🔷️Performances 2024 :
- 11M+ tonnes de céréales
- 640 000 tonnes de coton
- 97 000 tonnes de viande
- 113 000 tonnes de poisson
🔷️Mesures annoncées:
- Subventions :
- Coton (300 FCFA/kg)
- Engrais minéraux (14 000 FCFA/sac)
- Semences de maïs (1 500 FCFA/kg)
- Soutien à la mécanisation, pisciculture et crédit agricole
🔷️Objectif : Renforcer l’autosuffisance alimentaire et les chaînes de valeur locales.
🌎 Vertical farming—growing crops in stacked indoor layers—uses up to 95% less water than traditional agriculture, while reducing pesticide use and transportation emissions. Some modern vertical farms employ LED lighting and hydroponics, completely soil-free, to produce lettuce and herbs year-round in urban settings. ✨
#ecology⚡#technology⚡#agriculture
👉subscribe Interesting Planet
👉more Channels
🌎 The future of Earth’s ecology could be transformed by vertical farming—multistory indoor farms that use LED lighting and hydroponics to grow crops year-round. These farms use up to 95% less water than traditional agriculture and can be built in cities, reducing transport emissions and land use. ✨
#ecology⚡#technology⚡#agriculture
👉subscribe Interesting Planet
👉more Channels
🌎 The Amazon basin is home to “terra preta” soils—dark, fertile earth created by ancient humans mixing charcoal, bones, and compost. This enriched soil still boosts crop yields centuries later, showing early Amazon cultures mastered sustainable farming. ✨
#Amazon⚡#archaeology⚡#agriculture
👉subscribe Interesting Planet
News: #Ethiopia earns $288.48 million from horticulture exports in seven months, amid sector bottlenecks
Ethiopia has generated $288.48 million from the export of more than 160,000 tons of #horticultural products during the first seven months of the current Ethiopian fiscal year, the Ministry of #Agriculture announced, despite concerns raised by stakeholders over infrastructure gaps, logistics constraints, and land supply management.
The ministry disclosed the performance following a consultative meeting with relevant public institutions and local and foreign investors engaged in the horticulture sector to assess progress over the reporting period.
Minister of Agriculture Addisu noted that horticulture, alongside coffee, remains one of Ethiopia’s priority export commodities, highlighting its strategic importance in boosting foreign exchange earnings.
Ethiopia’s horticulture industry has faced mounting challenges in recent years, largely driven by security...
Read more: https://addisstandard.com/?p=55463
📹 VIDEO | Rice Producers Protest Agribusiness Pressure in Venezuela
Rice producers across Venezuela are taking to the streets ahead of the upcoming harvest, warning that prices offered by agroindustrial firms could leave many farmers unable to cover production costs.
Campesino groups say large conglomerates are using their control over silos, imports, and distribution to push prices down, while limited access to credit keeps farmers dependent on company financing.
After talks with producers, Agriculture Minister Julio León Heredia announced a provisional price. But campesino organizations warn they were barely represented in negotiations.
Click here to read our full report 👉🏾https://venezuelanalysis.com/news/venezuela-rice-producers-denounce-agribusiness-pressure-demand-govt-support-for-fair-prices/
#Agriculture#Peasants#Campesinos