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

Пребарај: #globaltrends

当前筛选 #globaltrends清除筛选
Crypto M - Crypto News

@CryptoM · Post #64981 · 10.04.2026 г., 12:48

🚀 Economist Win Thin Reflects on Global CPI Trends Economist Win Thin has observed that, in retrospect, the Consumer Price Index (CPI) data for March in most countries worldwide was slightly below expectations, with the exception of the United States. According to Jin10, many other countries are increasing fuel subsidies to alleviate the impact on consumers. However, Thin warns that this approach may lead to significant fiscal burdens, making it unsustainable in the long term. #Economist#CPI#GlobalTrends#FuelSubsidies#FiscalBurden#Inflation

EdgeMarket.AI 📣

@edgemarketai · Post #7987 · 09.02.2026 г., 19:28

🌍 One question. Global consequences. Will Russia and Ukraine reach a ceasefire by March 31, 2026? Diplomacy, pressure, fatigue — or escalation? Drop your take 👇 https://edgemarket.ai/bnb/social-media/Russia%20x%20Ukraine%20ceasefire%20by%20March%2031,%202026/statistics/69830479ff612403d86bf273 #Geopolitics#Ceasefire#WorldNews#GlobalTrends#ConflictAnalysis#FutureEvent

IELTS|Newspapers & Magazines|English

@emagzinewspars · Post #9653 · 03.12.2025 г., 08:21

#The_Fortune🇺🇸📕[PDF]⬇️ #December2025 #January2026 #Monthly_Magazines For learning, for free(dom). @backupofmagazines Global coverage this week tracks how rising tech power reshapes markets and geopolitics as China accelerates drug manufacturing, automation and green innovation with implications for global supply chains amid growing #Geopolitics tension. U.S. markets confront an expanding #AI boom, from Anthropic’s trust-first model to questions around Nvidia’s dominance, while investors chase new strategies in an increasingly volatile #MarketWatch environment. Culture and consumer shifts surface in Roblox’s evolution, the booming beauty sector and wellness travel trends. Meanwhile climate action, urban sustainability and energy transitions intensify worldwide under mounting #ClimateCrisis pressure, defining a rapidly changing global landscape shaped by #GlobalTrends.

IELTS|Newspapers & Magazines|English

@emagzinewspars · Post #9618 · 26.11.2025 г., 02:12

#The_Barron's 🇺🇸📕[PDF]⬇️ 24 #November2025 #Weekly_Magazines For learning, for free(dom). @backupofmagazines Europe’s renewed market momentum anchors this Barron’s issue, where analysts see brighter days ahead amid rising profits and shifting geopolitics—an outlook shaped by #MarketWatch forces and #GlobalTrends. Nvidia’s strong guidance fuels confidence in the #AI boom, even as investors navigate #Volatility across equities and buffer ETFs. Caution rises around India’s IPO wave, reinforcing a broader #RiskManagement mindset. With bond vigilantes returning and central-bank uncertainty growing, the magazine highlights why disciplined strategy remains essential in today’s #Finance landscape.

IELTS|Newspapers & Magazines|English

@emagzinewspars · Post #9561 · 17.11.2025 г., 03:17

#The_Science🇺🇸📕[PDF]⬇️ 13 #November2025 #Weekly_Magazines For learning, for free(dom). @backupofmagazines This issue dives into breakthroughs reshaping biology and energy as researchers confront rising geopolitical limits. From #AI-driven epigenetics to #SyntheticBiology advances, the issue tracks how innovation pushes ahead despite tensions over China-US research ties. New micro-robots navigating the bloodstream and faster-charging batteries highlight a surge in #DeepTech momentum. Climate resilience, #PandemicPreparedness, and EU chemical reforms underscore global policy stakes. Studies on dog domestication, brown dwarfs, and marine recovery after extinction broaden the scientific lens. A reminder that #ScienceMatters even as politics shift—innovation continues to define our shared future. #TechNews#GlobalTrends#ResearchUpdates

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.