Установить свойства виджета в 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
🚢Worley выполнит FEED-инжиниринг для газового проекта Aphrodite компании Chevron.
Инженерная компания Worley получила контракт от Chevron Cyprus Limited (дочерней структуры Chevron Corporation) на выполнение работ по front-end engineering design (FEED)и закупкам оборудования для разработки газового месторождения Aphroditeу побережья Кипра в Восточном Средиземноморье.
Контракт предусматривает проектирование полной инфраструктуры проекта, включая подводные системы, плавучую производственную установку (FPU), экспортный газопровод и береговой приемный терминал. Также Worley будет заниматься закупкой оборудования для морских и наземных объектов.
Работы выполняются на основе компенсационного контракта engineering & procurement и продолжат ранее выполненные компанией этапы pre-FEED и подготовки проекта. Завершение стадии FEED ожидается к декабрю 2026 года.
Месторождение Aphrodite, расположенное в блоке 12 исключительной экономической зоны Кипра, содержит примерно 3,5 трлн кубических футов газа и станет первым офшорным газовым проектом страны. Начало добычи планируется ориентировочно в 2032 году.
Оператором проекта выступает Chevron Cyprus (35%), партнёрами являются BG Cyprus (Shell) — 35% и NewMed Energy — 30%.
📌Worley Limited — международная инженерная и консалтинговая компания в сфере энергетики и инфраструктуры, основана в 1971 году в Австралии. Компания является публичной и торгуется на Australian Securities Exchange (ASX); крупнейшие акционеры — институциональные инвесторы.
#OffshoreGas#Chevron#Worley#EasternMediterranean#EnergyProjects
🔺Continuation from above
@rednile12
⚔️ Turkey: Strategic Catalyst
While Greek officials publicly deny targeting Turkey, the logic is clear:
▪️Turkish Blue Homeland doctrine
▪️Naval assertiveness near Cyprus and drilling disputes
▪️40,000–60,000 troops in northern Cyprus
▪️Expansion in Syria
The Xenophon concept is deterrence by coordination, raising the cost of Turkish escalation while avoiding overt provocation. Turkish responses online and politically reveal strategic irritation rather than indifference.
🛢️ EastMed & the U.S. Energy Play
The security and energy dimensions are inseparable. EastMed — signed in Athens in January 2020 — was designed to link Israeli and Cypriot gas directly to Greece and onward to Europe, bypassing unstable intermediaries and reducing Europe’s exposure to Russian energy coercion.
Consider the broader context:
🔹Nord Stream sabotage and closure of the Ukrainian transit corridor left Russia’s gas flowing via TurkStream, allowing Ankara to profit while Europe remained dependent.
🔹 U.S. President Trump explicitly pushed the EU to stop importing Russian gas while sabotaging Nord Stream, aiming to reroute Europe toward alternative suppliers.
🔹Analysts note the difference between Biden and Trump is one of style, not strategic logic — both administrations favored managing intermediaries over creating truly sovereign connectivity.
🔹 Other attempts, like IMEC linking India, the Gulf, and Europe, reveal the limits of Washington’s approach: symbolic agreements without Mediterranean anchors cannot secure reliable energy corridors, leaving Turkish leverage intact.
🇪🇬 Egypt: Bridge and Buffer
Israel’s growing gas cooperation with Egypt complements EastMed rather than undermining it:
▪️ Egypt provides an immediate, pragmatic export route via existing LNG terminals
▪️ EastMed remains the long-term, direct corridor to Europe
Together, they offer flexibility without reducing sovereignty. But Egypt’s role is also constrained: it is increasingly a logistics node in an Israel-centric Mediterranean security and energy order, limiting its diplomatic maneuvering, especially regarding Gaza.
🇵🇸 Palestine: Sidelined
Palestine remains absent from regional security and energy calculus. Gaza is treated as a permanent security zone, not a political partner, while Israel embeds itself into Mediterranean and European security networks.
Arab leverage erodes, and Palestine is reduced from a regional cause to a managed file.
🔻 Strategic Takeaways
🔹Xenophon Force: Multinational rapid response, signaling pro-Western deterrence, complicating Turkish ambitions.
🔹Energy Security: EastMed + Egypt LNG = sovereign flexibility for Europe, bypassing unstable intermediaries.
🔹U.S. Influence: Preference for managing intermediaries (Turkey, Ukraine, Central Asia) over eliminating dependency, risking strategic incoherence.
🔹Regional Impacts: Egypt partially integrated, Palestine structurally marginalized, Turkey forced to recalibrate.
This is not peace architecture. It is conflict management for the strong — and structural invisibility for the weak.
🔴Follow @rednile12 for critical geopolitical analysis
#RedNile_Geopolitics
#EasternMediterranean#XenophonForce#IsraelGreeceCyprus#Turkey#Egypt#Palestine#EastMedPipeline#EnergyGeopolitics#BlueHomeland#NordStream#USEnergyStrategy#MediterraneanSecurity#RedNileMedia