TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #381 · 23 окт.

Установить свойства виджета в 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

Hashtags

Резултати

Пронајдени 3 слични објави

Пребарај: #redbook

当前筛选 #redbook清除筛选
EKOLOG.UZ| ENG

@ekologuzenglish · Post #11767 · 01.03.2026 г., 14:59

#RedBook🌷 Tulipa affinis (Relative Tulip) A rare endemic plant of the Western Pamir-Alay region, found only in limited areas. Its bright red flower with a black center and yellow border makes the plant especially striking — but this beauty is also one of the reasons it is often destroyed. 📍Distribution In Uzbekistan, it grows in the Jizzakh, Samarkand, and Navoi regions — on the Turkestan and Malguzar mountain ranges and in the Nurata Mountains. It is also found in Kyrgyzstan and Tajikistan. The plant grows on rocky slopes, in gorges, and among shrubs and juniper woodlands. 🌱Plant characteristics ▫️ Perennial bulbous plant, 15–25 cm tall ▫️ Blooms in April–May ▫️ Reproduces by seeds and vegetatively ▫️ Occurs rarely in nature — as single plants or small groups ⚠️Why the species is under threat The main reasons for the population decline are mass collection of flowers and livestock grazing, which destroy the plant’s natural habitat. 🌿Conservation status The plant has been cultivated in the Botanical Garden of the Academy of Sciences of the Republic of Uzbekistan since 1957 and is protected in Zaamin State Reserve and Nurata State Reserve. 💚 Protecting rare plants is an important part of preserving biodiversity. Take care of nature and do not pick wild flowers. ☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot Instagram | Facebook | Twitter | Sayt | Youtube.

Hashtags

EKOLOG.UZ| ENG

@ekologuzenglish · Post #10738 · 12.12.2025 г., 01:04

📕#RedBook WILD GRAPEVINE Latin name: Vitis vinifera L. Status: Category 3 – Rare species with a fragmented range in Uzbekistan 🌿 Description A climbing woody vine reaching up to 30 meters in length. Leaves are simple, nearly round, 3–5-lobed or palmately divided, with a heart-shaped base; edges are serrated or crenate. The inflorescence is a dense or loose panicle. Fruits vary in color and shape. Flowers in May–June, fruits ripen in July–October. 📍 Distribution In Uzbekistan: – Jizzakh, Surkhandarya, Tashkent regions: ▪️ Nurata range (Gurdara and Bolosoy gorges) ▪️ Gissar range (Sangardak and Tupalang river basins) – Western Tien Shan: Pskem, Ugam, Korzhantau, Chatkal ranges Also found in: – Tajikistan – Kyrgyzstan – Kazakhstan 🌱 Habitat Grows along riverbanks, in gorges, on gravelly and fine-soil mountain slopes. 🔢 Population Occurs as solitary plants or in small clusters. ♻️ Reproduction Reproduces by seeds and vegetatively. ⚠️ Threats and Causes of Decline – Trampling and damage caused by grazing livestock – Use of the plant as firewood These factors lead to a steady reduction in population and habitat range. 🌿 Domestication and Importance Cultivated in all botanical gardens of Central Asia, in specialized horticultural research plots, and at breeding stations for developing new varieties. 🛡 Conservation Measures – Protected in the Nurata and Chatkal State Nature Reserves – Under protection in the Ugam–Chatkal National Park ☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot Instagram | Facebook | Twitter | Sayt | Youtube.

Hashtags

EKOLOG.UZ| ENG

@ekologuzenglish · Post #11614 · 15.02.2026 г., 11:03

🦅 Peregrine Falcon — the fastest bird in the world The peregrine falcon can reach speeds of up to 390 km/h during a dive. These majestic predators hunt birds and small mammals, playing a vital role in maintaining the balance of ecosystems. ❗️ Important: the peregrine falcon is listed in the Red Book of Uzbekistan. Its population is under threat due to habitat destruction, poaching, and environmental pollution. 🌿 Protecting peregrine falcons is a contribution to preserving the biodiversity and future of our country’s nature. #PeregrineFalcon#RedBook#ProtectNature#RareBirds#Biodiversity ☘️ Follow the latest environmental news on @ekologuz. Subscribe and send your suggestions and feedback via @eklguz_bot