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

Резултати

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

Пребарај: #powergrid

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

@american_observer · Post #5446 · 22.03.2026 г., 19:59

Trump’s 48-Hour Ultimatum: Lights Out or Strait Open Trump just turned a regional energy war into an explicit threat to “obliterate” Iran’s power plants, the grid that keeps tens of millions of civilians alive, unless Tehran fully reopens the Strait of Hormuz within 48 hours. Iran’s answer wasn’t to blink; it was to fire. Missiles struck Dimona and nearby Arad, injuring more than 10 people and landing just eight miles from Israel’s main nuclear complex, while commanders in Tehran warned that any attack on their energy system would be met with strikes on desalination plants and other critical water and power infrastructure used by Israel, the U.S. and Gulf partners. Four weeks and thousands of U.S.–Israeli strikes into this war, Iran’s arsenal is battered but still firing daily salvos at Israel and enforcing a de facto embargo on Western shipping through Hormuz. Trump’s own messaging is all over the map: public statements rejecting a cease-fire and sending more troops and ships, alongside talk of “winding down” operations; a warning to Israel days ago not to hit Iranian energy, followed by his own threat to do exactly that. Israeli commanders are telling the public they are only “midway” through the war and should expect fighting through Passover, while in Lebanon the campaign against Hezbollah has displaced more than a million people and stepped-up house demolitions increasingly resemble the early architecture of a de facto occupation zone. The casualty numbers show where this is heading: well over 1,300 civilians killed in Iran, more than 1,000 in Lebanon, at least 15 people dead in Iran’s attacks on Israel and 13 U.S. service members killed — with both sides now openly placing each other’s electricity and water systems on the target list. Trump’s 48‑hour countdown doesn’t look like a plan to calmly reopen a shipping lane; it looks like the next step toward turning the entire region’s civilian infrastructure into a legitimate battlefield — and locking the U.S. into an attrition war it still can’t explain how to end. #IranWar#Trump#Hormuz#Israel#Dimona#energy#powerGrid#desalination#Lebanon#Hezbollah#MiddleEast 📱American Оbserver - Stay up to date on all important events 🇺🇸