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 слични објави

Пребарај: #wildfire

当前筛选 #wildfire清除筛选
Amazing Geography 🌍

@amazingeo · Post #619 · 07.02.2026 г., 20:31

🌍 In 2021, Europe's Aegean wildfires generated smoke that reached as far as the North Pole—a rare journey showing how natural disasters can have effects thousands of kilometers away. ✨ #disasters⚡#wildfire⚡#atmosphere⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Reuters: World

@reutersworldchannel · Post #149346 · 14.10.2021 г., 08:20

Firefighting crews battle wildfire near Reagan ranch California firefighters took advantage of a break in strong winds to get aircraft aloft and dump retardant on a fast-moving wildfire that was within a half mile of former President Ronald Reagan's ranch, officials said. #News#Reuters#Wildfire#California Subscribe: http://smarturl.it/reuterssubscribe Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled. Get the latest news on: http://reuters.com/ Follow Reuters on Facebook: https://www.facebook.com/Reuters Follow Reuters on Twitter: https://twitter.com/Reuters Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en ➖@reutersworldchannel➖

America 🇺🇸 News & Politics

@America · Post #10569 · 29.04.2026 г., 02:19

🔥😱GEORGIA WILDFIRE EXPLODES TO $22,600 ACRES 🔹 Brantley County fire doubles overnight from $11K to $22.6K acres — only 6% contained 🌲 🔹 90 homes destroyed in worst residential wildfire loss in Georgia history 🏠💔 🔹 Evacuation orders for 6,000 residents as winds fuel rapid spread through dry forest 🌪️ 🔹 Emergency crews from 5 counties battling flames with limited water access 🚒 🔹 Governor declares state emergency, requesting federal aid for disaster relief 🆘 This is why climate change isn't just talk — it's burning down America piece by piece 🔥🇺🇸 #Georgia#wildfire#ClimateChange#EmergencyAlert @america

Venture Village Wall 🦄

@venturevillagewall · Post #3406 · 18.12.2024 г., 12:10

$30M Funding for Stand Insurance Stand Insurance secured $30M in funding on December 16, 2024. This company specializes in providing tailored coverage for high-value homes, employing science-backed solutions to protect against wildfires in California's vulnerable regions. #Funding#Insurance#Wildfire#California#HomeProtection#StandInsurance#HighValueHomes

IELTS|Newspapers & Magazines|English

@emagzinewspars · Post #9281 · 05.10.2025 г., 16:31

#The_Science🇺🇸📕[PDF]⬇️ 2 #October2025 #Weekly_Magazines For learning, for free(dom). @backupofmagazines This issue explores breakthroughs in #cancer treatment with radioisotope drugs, urgent debates on #wildfire management, and novel insights into #quantum battery charging. Features include fossil repatriation from the Netherlands to #Indonesia, brain nanotube networks, and volcanic unrest in Chile. Research spans from ancient #DNA revealing mammoth evolution to quantum optics reshaping imaging. With perspectives on #climate change, plastics policy, and microbial plant colonization, the issue highlights science at the intersection of #innovation, environment, and global policy.

IELTS|Newspapers & Magazines|English

@emagzinewspars · Post #9463 · 03.11.2025 г., 03:27

#The_National_Geographic🇺🇸📕[PDF]⬇️ #November2025 #Monthly_Magazines For learning, for free(dom). @backupofmagazines This issue tours big frontiers: a colossal #NuclearFusion tokamak in France promises star power on Earth; botanists curate the world’s deadliest garden; a teenage Sherpa resets who belongs on alpine peaks; macro art peers through a bug’s eye; new science reframes adult #ADHD; crested gibbons show robotlike dances; wildfire imagery from the #SierraNevada; archaeologists ink themselves to decode ancient tattoos; and medics test human hibernation for deep-space care. Essential reading for explorers and pragmatists alike. #NationalGeographic#Climate#Energy#Biodiversity#Wildfire#Photography#Neuroscience#Space#Innovation#Science#Sustainability#Tokamak#Fusion amid accelerating #AI research and #GlobalTrends, shaping tomorrow’s decisions.