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

Резултати

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

Пребарај: #nwo

当前筛选 #nwo清除筛选
Indian Development News 🇮🇳

@developmentnewsindia · Post #44329 · 02.05.2026 г., 10:27

Breaking: At the Peace Dialogues held between Pakistan and Afghanistan in Turkey, IHH, the org hosting the dialogue in Turkey, removed PoK, Balochistan and parts of Khyber Pantukhwa from Pakistan's map. #NWO#Geopolitics

Indian Development News 🇮🇳

@developmentnewsindia · Post #43826 · 20.04.2026 г., 04:43

BREAKING 🇦🇪⚡🇺🇸 A post on X by Abdulkhaleq Abdullah, adviser to the UAE president: “The UAE no longer needs the United States to defend it, as it has proven during Iranian aggression that it is fully capable of defending itself with competence.” “It is time to consider closing U.S. bases in the Arabian Gulf, as they are a burden on the UAE.” #Geopolitics#NWO

Indian Development News 🇮🇳

@developmentnewsindia · Post #43821 · 20.04.2026 г., 02:36

UAE to Trump Administration: "You started this war; if we run short of USDs as a result of it, either you will give us USD swap lines, or we will be forced to start transacting oil and gas in CNY and other currencies." -Via Wall Street Journal #NWO#geopolitics

Indian Development News 🇮🇳

@developmentnewsindia · Post #43877 · 21.04.2026 г., 07:14

🇯🇵 Prime Minister of Japan Sanae Takaichi "Today, we amended the 'Three Principles on Transfer of Defense Equipment and Technology' and their 'Guidelines for Implementation.' Until now, the overseas transfer of domestically produced finished products had been limited to search and rescue, transportation, surveillance, mine countermeasures (so-called 'five categories'), but with this amendment, transfers of all defense equipment will in principle become possible. In an increasingly severe security environment, no single country can now protect its own peace and security alone, and partner countries that support each other in terms of defense equipment are necessary." #InternationalNews#NWO

Indian Development News 🇮🇳

@developmentnewsindia · Post #43849 · 20.04.2026 г., 11:44

The US government has called on the defense contractor V2X to evacuate its employees from Kuwait and Iraq, warning the company that they could be targeted by Iran-backed militias, four sources said. #InternationalNews#NWO https://www.theguardian.com/world/2026/apr/20/defense-contractor-evacuate-iraq-kuwait

Indian Development News 🇮🇳

@developmentnewsindia · Post #43480 · 11.04.2026 г., 20:17

🇺🇸💰💵 US Dollar now represents ~46% of global FX and gold reserves, the lowest in at least 26 years. This percentage has declined -15 points since 2017. Excluding gold, the US Dollar makes up 57% of global reserve currencies, the lowest since 1994, according to IMF data. This comes as central banks have aggressively accumulated gold and diversified into other currencies. The last time the US Dollar fell below 50% of global reserves was in 1990-1991, a period marked by elevated inflation, a recession, and a crisis of confidence in the US economy. #InternationalNews#NWO

Политическая П

@politpe · Post #19932 · 16.02.2026 г., 19:25

🌎#nwo#макро Рэй Далио на Мюнхенской конференции по безопасности: - старый мировой порядок, установленный после 1945 года уже объявлен мертвым большинством мировых лидеров - сейчас мы находимся на «6-м этапе» большого цикла, где нет правил, сила — это право, и великие державы сталкиваются друг с другом - экономические войны обычно предшествуют настоящим войнам, где стреляют - в 1930-е годы были торговые войны, технологические войны, войны капитала и геополитические войны, продолжавшиеся около десяти лет, а потом в 1939 году началась настоящая война mt в max

12
ПретходнаСтраница 1 од 2Следна