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

Резултати

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

Пребарај: #mapping

当前筛选 #mapping清除筛选
Город на карте

@geomapers · Post #391 · 20.06.2025 г., 09:26

📍Думали ли Вы о Римской империи сегодня? Империя охватывала большую территорию, но в те времена дорога занимала много времени. Например: • Путь из Рима в Александрию зимой занимал в 4 раза больше времени • Доставка вина из Помпей (250 км) в Рим составляла 55% его стоимости • Решение о войне с Парфией зависело не от расстояния, а от цены провизии 🎓Стэнфордский университета запустил проект ORBIS — цифровую модель, которая показывает дороги и позволяет строить маршруты в Римской Империи с учетом времени (сезонов, погодных условий, расстояния), стоимости (налоги, фрахт кораблей, корм для животных), риски (пираты, штормы, горные перевалы). Проект: https://orbis.stanford.edu/ В летнее время самый быстрый маршрут из Рима в Лондиниум пешком (30 км в день) занимал почти 27 дней, учитывая морские перемещения из Рима на юг современной Франции и дальше через Бискайский залив. Зимой 42 дня. В некоторых случаях самым дешевым способом передвижения были ослы, особенно по горным тропам #mapping

Hashtags

Amazing Geography 🌍

@amazingeo · Post #684 · 07.04.2026 г., 20:31

🌍 The point where 60° north latitude meets 60° east longitude is in a remote forest of Russia—this rare intersection is called the "triple 60s" and has no nearby settlements or roads. ✨ #coordinates⚡#geography⚡#mapping⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #562 · 07.01.2026 г., 20:31

🌍 The intersection of four whole-degree geographic coordinates (latitude and longitude) on land is extremely rare. One of the only land spots where this happens is near Lake Chad in central Africa. ✨ #coordinates⚡#geography⚡#mapping⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

纯情男高

@hanzichen · Post #1470 · 27.12.2025 г., 23:58

city-roads city-roads is a browser-based mapping tool that draws every road in a selected city as a single, clean line map. After a user enters a city name, it retrieves the city’s road geometry from OpenStreetMap and renders the full street network in the browser, making it useful for exploring urban layouts, comparing city structures, and creating visually striking map graphics. 🔗 Links: - Website - Screenshots - Features - Source code Developer: Andrei Kashcha ❤️ Support the Project If this project makes your life easier, here are a few quick ways to show some love: ⭐ Star the repo/app ☕ Buy a coffee for the developer 🛠 Contribute code, issues, or pull-requests 🏷 Tags: #Website#Utilities#Mapping

Mappasaurus Official Channel

@mappasaurusofficial · Post #236 · 06.04.2025 г., 14:15

Centralized mapping struggles with limited data sources, leading to inaccurate information and missed turns, especially in dynamic environments. We at #Mappasaurus offer a solution with our decentralized OS. User-contributed data enriches #maps with real-time knowledge and real-time updates. #Blockchain Technology allows for a more accurate, adaptable, secure and user-driven future. Join us to explore how Mappasaurus is revolutionizing #mapping. 🤑Join the Game here: @MappasaurusAppBot Follow us on: Twitter | Instagram | Medium | Youtube | Linkedin | Earn 🌍Global Communities

Amazing Geography 🌍

@amazingeo · Post #23 · 10.08.2025 г., 13:12

🌍 The intersection of 0° latitude and 0° longitude is called "Null Island." It's marked on maps but sits in the Gulf of Guinea, with only a weather buoy at this exact ocean spot. ✨ #coordinates⚡#mapping⚡#ocean⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍

Amazing Geography 🌍

@amazingeo · Post #559 · 06.01.2026 г., 12:31

🌍 In 2019, explorers mapped more than 19,000 square kilometers of the Indian Ocean seafloor, revealing hundreds of new undersea mountains and deep valleys never before seen by humans. ✨ #exploration⚡#mapping⚡#ocean⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #376 · 15.10.2025 г., 18:31

🌍 In 2022, a team used autonomous underwater robots to explore parts of the Indian Ocean floor never mapped before, discovering hundreds of previously unknown seamounts hidden beneath the waves. ✨ #exploration⚡#ocean⚡#mapping⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #145 · 30.08.2025 г., 16:12

🌍 In 2019, explorers mapped over 20,000 square kilometers of the ocean floor in just one year using modern sonar. Much of the seafloor remains unmapped and full of geographic mysteries. ✨ #exploration⚡#mapping⚡#ocean⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #349 · 08.10.2025 г., 20:31

🌍 The Philippines is the world’s second-largest archipelago, with over 7,600 islands. Many of its islands have never been officially named or mapped due to their remote locations. ✨ #islands⚡#archipelago⚡#mapping⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #683 · 06.04.2026 г., 20:31

🌍 The oldest known map carved on stone was found in Europe and dates back over 4,000 years. It shows a planned landscape with fields and waterways carefully etched by early mapmakers. ✨ #cartography⚡#history⚡#mapping⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

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