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

Резултати

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

Пребарај: #russiannature

当前筛选 #russiannature清除筛选
Learn RCRussian🤍💙❤️

@learnRCRussian · Post #5582 · 20.10.2025 г., 12:00

The Northern Lights have reached the Moscow region! 🔻In a spectacularly rare event, the aurora borealis was visible even near Moscow last weekend. 🔻The heavenly glow was observed in the Arkhangelsk, Kostroma, and Moscow regions. The sky was also lit up with green and orange light in the Leningrad region. 🔻A stunning natural light show, much further south than usual! Videos, photos: the Internet #Russiannature 😎RCR | Support | Boost

Learn RCRussian🤍💙❤️

@learnrcrussian · Post #4604 · 30.04.2025 г., 16:00

💙Dolphins near the coast of Balaklava, Crimea 🇷🇺В этом видео всё прекрасно: изумительная палитра моря, сливающегося с небом, тёмные силуэты скользящих в воде плавников, угрюмые скалы. Так хочется быть частью этого мира! А вам нравится? 🇬🇧Everything in this video is perfect: the amazing palette of the sea merging with the sky, the dark silhouettes of fins gliding through the water, the somber cliffs. I so want to be a part of this world! Do you like it? Video: kulikov_alex5 #Russiannature 😎RCRussian | Support | Boost

Russian Embassy in Asmara

@rusembasmara · Post #678 · 09.04.2026 г., 09:31

🇷🇺RUSSIAN NATURE🇷🇺 🏞️The Putorana Plateau is one of the most mysterious and picturesque places in Russia. Located in the northwestern part of Krasnoyarsk Krai, this region feels untouched by time: vast basalt plateaus, deep canyons and thousands of waterfalls define its landscape. 💧It is often called «the land of ten thousand lakes and waterfalls». In terms of waterfall density, the plateau has no equal in Russia. One of them, the Talnikovy Waterfall, is considered the highest in the country. 🏅The Putorana Nature Reserve is a UNESCO World Heritage Site that attracts researchers, photographers and seekers of unexplored wilderness. 🏔️Many people dream of visiting this region. For hundreds of kilometers, there are only mountainous areas, deep gorges and intricate networks of rivers, lakes and waterfalls. Helicopter tours and river rafting are especially popular, though some travelers also venture out on hiking expeditions. 🤗Visit Russia and set out on a journey! #RussianNature#Russia

Learn RCRussian🤍💙❤️

@learnRCRussian · Post #5468 · 22.09.2025 г., 19:35

🧡Somewhere in Russia... • На закате (НА + Prepositional) [na za-ka-te] At sunset, at dusk • Вечером (adverb) [ve-chi-ram] In the evening • На исходе дня (НА + Prep.+Gen.) [na is-khho-di dnya] At the end of the day ✨Всем добра! #Russiannature #useful_vocabulary 😎RCR | Support | Boost

Learn RCRussian🤍💙❤️

@learnRCRussian · Post #6249 · 01.03.2026 г., 16:00

Аптекарский огород Apothecary's Garden 🌷This is a garden where medicinal plants are grown. 🌷Historically, these were pharmacy gardens established by Peter the Great in the early 1700s to grow herbs for medicines. 🌷Today, it refers to Moscow's oldest botanical garden (founded 1706), now a branch of Moscow State University and a popular park where you can see beautiful flowers, exotic plants, and even a 300-year-old larch tree! Video: moscowmi #brief_and_interesting #Russiannature 🟠RCR | Support | Boost

ПретходнаСтраница 1 од 5Следна