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

Резултати

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

Пребарај: #diving

当前筛选 #diving清除筛选
Interesting Planet 🌍

@interesting_planet_facts · Post #485 · 02.08.2025 г., 13:22

🌎 Along the Antarctic coast, Weddell seals can dive over 600 meters deep and hold their breath for up to 90 minutes. Special blood proteins store extra oxygen, letting them hunt under ice where few predators can reach. ✨ #antarctica⚡#mammals⚡#diving 👉subscribe Interesting Planet

🗺 Travel the World | Private Expeditions

@expeditionsworldwide · Post #562 · 24.07.2024 г., 18:33

🌊Dive Into Adventure with 5elementos.expeditions! Ready to explore the breathtaking underwater world? Join our scuba diving expedition and discover some of the most stunning dive sites out there! With our professional dive instructors, top-notch equipment, and the best team around, you’ll experience the ocean like never before. ❓What to Expect: - Expert guidance from experienced instructors - Modern, high-quality diving equipment - An unforgettable adventure in stunning destinations - Opportunities to learn more about marine life - Emotions and memories that will last a lifetime Dive into the adventure and book your spot today! DM us to learn more and reserve your place on our next expedition #ScubaDiving#Diving

Одна из жемчужин ЮАР — Марико Уг, потрясающее место для любителей фридайвинга. Система пресноводных пещер расположена в Северо-Западной провинции. Температура воды в течение всего года колеблется от 20 до 24 °C, что делает её идеальной для длительных погружений. Любители приключений съезжаются сюда со всего мира, чтобы получить необыкновенный опыт и незабываемые впечатления. _____________ One of many South Africa's gems is the Marico Oog, a captivating destination for freediving enthusiasts. This freshwater cave system is situated in the North West Province. The water temperature remains stable throughout the year, ranging between 20°C to 24°C (68°F to 75°F), making it ideal for extended dives. This diving offers an unforgettable underwater experience for adventurers seeking to explore a hidden world beneath the surface. #nature#sport#diving #природа#спорт#дайвинг Видео/Videos: https://t.me/woohworld/460, https://www.youtube.com/watch?v=jivOcP720VY.

Одна из жемчужин ЮАР — Марико Уг ✨ Потрясающее место для любителей фридайвинга и спокойных глубоких погружений. Система пресноводных пещер расположена в Северо-Западной провинции. Температура воды держится от 20 до 24 °C круглый год, что делает её идеальной для длительных погружений. Любители приключений съезжаются сюда со всего мира, чтобы получить уникальный опыт и незабываемые впечатления. 🌍💦 #Природа#Спорт#Дайвинг#SouthAfrica#Freediving#Adventure _________________ One of South Africa’s true gems — the Marico Oog ✨ A captivating destination for freediving enthusiasts. This freshwater cave system is located in the North West Province. With water temperatures ranging from 20°C to 24°C (68°F to 75°F) all year round, it’s perfect for long and relaxing dives. Adventurers travel here from around the globe to enjoy an unforgettable underwater experience. 🌍💦 #Nature#Sport#Diving#SouthAfrica #Freediving#Adventure 📹https://t.me/woohworld/460 📹https://www.youtube.com/watch?v=jivOcP720VY

🐙Oscar-Winning My Octopus Teacher – A Deep Dive into Unlikely Friendship 🇿🇦 Burnt out and emotionally drained, filmmaker Craig Foster found healing in the ocean off Cape Town. Over eight years, he formed an extraordinary bond with a wild octopus — a creature that became his unexpected teacher. 🎬My Octopus Teacher (2021) is a beautifully shot documentary about connection, balance, and rediscovering the natural world. 🏆 The film won the Oscar and BAFTA for Best Documentary Feature — a must-watch for nature lovers and seekers of meaning. 📽Official trailer (with Russian subtitles): 🔗https://www.youtube.com/watch?v=yP-dgd852Ro #MyOctopusTeacher#Documentary#NatureFilm#OceanLife#CapeTown#SouthAfrica#OscarWinner#BAFTA#Wildlife#Diving#Mustwatch

🗺 Travel the World | Private Expeditions

@expeditionsworldwide · Post #488 · 03.07.2023 г., 13:03

🫶 Dear subscribers! We delighted that you're following our channel! On our channel, you'll find everything about travel! By using hashtags, you can easily find the content that interests you. CHANNEL CONTENT: 📹#videoclips 🧭#expedition 🏔️#hiking 🤿#diving 🧨#unusualplaces ⛩#bridges 🏔#mountains ⌛️#facts ✈️#airplanecemeteries 🗻#hills 🏜#discoveries 🏖#beaches 🈴#China 🕌#India 💒#temples 🏤#architecturalmasterpieces 🚆#journeys 🏜#vacations 🎇#UNESCO ⛰#cliffs 🌋#canyon 🌊#lakes 🏢#skyscrapers ⛲️#waterfalls ⛴#dam 🏕#inaccessibleplaces 🌋#volcano 🚀#traveladvice 🌊#sea 🌲#forest 🏝#island 🌅#desert 🌫#ponds ⛰#cave ⭐️#travelhacks ⛺️#nationalpark Thank you for being a part of our travel community! Happy exploring! 🪐Discover upcoming expeditions — https://4elementos.shop