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

Резултати

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

Пребарај: #fuelprices

当前筛选 #fuelprices清除筛选
American Оbserver

@american_observer · Post #5519 · 31.03.2026 г., 13:02

Macron Sounds Brave on Israel, Frugal at Home Emmanuel Macron condemned Israel over the blocked Palm Sunday procession in Jerusalem, calling freedom of worship something that must be guaranteed for all religions. Fair enough — except this is the same French president whose government is now offering only tightly targeted fuel aid because, as France’s central bank put it, there is “no more money” for broad subsidies. That’s the modern European posture in miniature: moral thunder abroad, budget discipline at home. Macron can scold Israel for trampling holy sites, but when French drivers and businesses get squeezed by the oil shock, Paris reaches for a scalpel, not a blanket. The principles are grand; the compensation is minimal. And that tension is the point. The Middle East crisis has pushed fuel prices higher across Europe, but France’s answer has been cautious, targeted relief rather than the old-school political sugar rush of big subsidies. So Macron gets to play the global conscience while his own finance people remind everyone that righteousness does not pay the diesel bill. #Macron#France#Israel#Jerusalem#fuelprices#MiddleEast#politics 📱American Оbserver - Stay up to date on all important events 🇺🇸

🚢Рекордные премии на бункер вынуждают суда искать топливо в азиатских хабах. Резкий рост цен на морское топливо на фоне конфликта на Ближнем Востоке привёл к серьёзным сбоям в бункеровке судов в крупнейших азиатских портах. По данным участников рынка, стоимость топлива выросла более чем в два раза по сравнению с уровнем до начала конфликта. В крупнейшем мировом бункеровочном хабеСингапуре цена низкосернистого топлива превысила $1 000 за тонну, а премии на спотовом рынке достигли рекордных уровней — значительно выше отметки $200 к базовым котировкам. Суда всё чаще сталкиваются с задержками при бункеровке, что может привести к росту загруженности портов Сингапура, Шанхая и Нинбо-Чжоушань. Перенаправление судов из-за ограничений транзита через Ормузский пролив также увеличивает поток трафика в азиатские порты. По оценке аналитиков, многие поставщики переходят на спотовые продажи, избегая долгосрочных контрактов из-за высокой волатильности цен. Дополнительное давление на рынок создаёт сокращение поставок топочного топлива из стран Ближнего Востока. Для судоходной отрасли это означает рост операционных затрат, увеличение времени ожидания в портах и дополнительное давление на фрахтовые ставки. 📌Linerlytica — аналитическая компания в сфере морской логистики и контейнерных перевозок, специализирующаяся на анализе глобальных торговых потоков и портовой статистики. Компания является частной и принадлежит основателям и инвесторам. #Bunkering#FuelPrices#SingaporePort#ShippingCosts#MaritimeTrade

Crypto M - Crypto News

@CryptoM · Post #64659 · 09.04.2026 г., 13:03

🚀 Poland's Central Bank Highlights CPI Risks from Fuel Price Policies Poland's central bank has identified fiscal policies and regulations related to fuel prices as ongoing risks to the Consumer Price Index (CPI). According to Jin10, these factors continue to pose challenges to the country's inflation outlook. The central bank's assessment underscores the importance of monitoring fuel-related policies as they can significantly impact inflation rates. Policymakers are urged to consider these risks in their economic strategies to ensure stability in the CPI. #Poland#CentralBank#CPI#FuelPrices#Inflation#FiscalPolicies#EconomicStability#InflationRisks

Crypto M - Crypto News

@CryptoM · Post #65391 · 13.04.2026 г., 04:34

🚀 Middle East Conflict Could Severely Impact Australia's Economy, Expert Warns Calculations and analyses are currently underway regarding the potential impact of the ongoing Middle East conflict on Australia's fuel prices and economic growth. According to Jin10, David Rumbens, a partner at Deloitte Access Economics, has stated that the worst-case scenario would severely affect Australia. A prolonged conflict could drive oil prices up to $175 per barrel, with inflation rates reaching 7.5% by the end of the year. The ultimate outcome could see Australia's unemployment rate rise to 6.8%, while the GDP growth rate could decline by 2.8%. Notably, none of the proposed scenarios indicate an unemployment rate below 5.0%. #MiddleEastConflict#AustraliaEconomy#FuelPrices#EconomicGrowth#Inflation#Unemployment#GDPGrowth#OilPrices#DavidRumbens#DeloitteAccessEconomics

Crypto M - Crypto News

@CryptoM · Post #64509 · 09.04.2026 г., 04:36

🚀 Macquarie: Southeast Asia Fuel Prices Surge Amid Iran Conflict Macquarie stated in a stock research report on April 9 that fuel prices in Southeast Asia have significantly increased and are unlikely to return to pre-Iran conflict levels in the short term. According to Jin10, the firm remains optimistic about energy-related industries, including alternatives like crude palm oil, while advising against non-essential consumer goods, hotels, and leisure sectors. Macquarie noted that after a substantial rise in oil prices, it typically takes about six months for consumer inflation to show a significant increase. The report also mentioned that energy subsidies in Malaysia and Indonesia might temporarily mitigate the negative impact on consumers. #SoutheastAsia#FuelPrices#IranConflict#Macquarie#EnergyIndustries#CrudePalmOil#ConsumerInflation#OilPrices#EnergySubsidies#Malaysia#Indonesia