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

Резултати

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

Пребарај: #diplomacy

当前筛选 #diplomacy清除筛选
Interesting Planet 🌍

@interesting_planet_facts · Post #398 · 23.07.2025 г., 18:22

🌎 In ancient China, giant panda pelts were considered symbols of peace and friendship. Emperors gifted them to rival kingdoms as precious gestures, showing diplomacy in action through nature’s rarest bear. ✨ #history⚡#animals⚡#diplomacy 👉subscribe Interesting Planet

America 🇺🇸 News & Politics

@America · Post #10562 · 27.04.2026 г., 13:02

🚨🇺🇸TRUMP TELLS IRAN "CALL US" AS PUTIN HOSTS TEHRAN'S TOP DIPLOMAT 🔹 Iranian Foreign Minister Abbas Araghchi lands in St. Petersburg today for emergency talks with Putin 🇷🇺 🔹 Trump abruptly canceled US-Iran face-to-face meeting scheduled in Pakistan, blaming Tehran's "excessive demands" 📞❌ 🔹 Nine-week conflict continues with mutual blockades choking energy markets — oil prices surge nationwide 💰⛽ 🔹 Strait of Hormuz remains partially closed as Iran seeks Russian backing after US diplomacy collapsed 🚢🔒 "The ball is in their court — call us when you're ready to be serious," Trump signals 📱 This is getting messy fast 😬🔥 #USNews#Iran#diplomacy @america

DiplomatKa

@Diplomatika · Post #146 · 05.01.2021 г., 06:04

Faces of #Uzbekistan#Diplomacy Ambassadors, permanent representatives and general consuls of Uzbekistan abroad with the First Deputy Chair of the Senate of the Parliament Sodyq Safaev and the Deputy Minister of Foreign Affairs Sherzod Asadov, after the seminar training organised by the Senate. P.S. Could you find only two women? @Diplomatika

America 🇺🇸 News & Politics

@America · Post #10448 · 02.04.2026 г., 13:03

🚨🇺🇸U.S. INTEL: IRAN REJECTS PEACE TALKS 🔹 Multiple intelligence agencies assess Tehran unwilling to negotiate seriously 🕵️‍♂️ 🔹 Iran believes it's winning, doesn't trust Trump after previous attacks mid-negotiations 💪 🔹 Trump claims military will wrap up Iran campaign within 2-3 weeks ⏰ 🔹 President threatens to bomb ALL Iranian power plants if no deal - potential war crime ⚡ 🔹 Tehran foreign ministry denies asking for ceasefire despite Trump's progress claims 🗣️ Iran wants real peace talks, not temporary fixes according to Pakistani officials! This war is FAR from over 😤🔥 #USNews#Iran#Trump#diplomacy @america

Amazing Geography 🌍

@amazingeo · Post #671 · 24.03.2026 г., 20:31

🌍 The Arctic Council brings together eight countries to manage Arctic resources and navigate disputes, making this region one of the world’s best examples of peaceful geopolitical cooperation. ✨ #geopolitics⚡#Arctic⚡#diplomacy⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Venezuelanalysis

@venanalysis · Post #1629 · 02.07.2024 г., 19:00

The Venezuelan government accepted Washington’s offer to restart dialogue only weeks ahead of presidential elections on July 28. President Maduro emphasizes any talks will have Venezuela's sovereignty as a starting point. Full story: https://venezuelanalysis.com/news/venezuela-to-restart-direct-talks-with-us-maduro-announces/ #Venezuela#UnitedStates#Diplomacy

America 🇺🇸 News & Politics

@America · Post #10385 · 14.03.2026 г., 05:37

🚨🇨🇺🇺🇸CUBA CONFIRMS SECRET TALKS WITH TRUMP ADMINISTRATION 🔹 Cuban President Díaz-Canel publicly admits holding bilateral talks with US officials 🤝 🔹 Discussions aim for historic economic deal - biggest opening since 1961 revolution 💰 🔹 Cuba releases 51 prisoners as Vatican-brokered goodwill gesture ahead of negotiations 🕊️ 🔹 Trump threatens "friendly takeover" if Cuba refuses to make deal with Washington 💪 🔹 Island faces fuel crisis with NO oil shipments for 3 months due to US blockade ⛽ 🔹 Secretary Rubio reportedly in secret talks with Raul Castro's grandson Raulito 🤐 This could END 65 years of Cold War hostility - but at what price? 🔥🌎 #Cuba#diplomacy#Trump @america

Venezuelanalysis

@venanalysis · Post #2323 · 31.03.2026 г., 18:59

📰 NEWS | Venezuela Reclaims US Diplomatic Venues as Rodríguez Promotes ‘Faith Diplomacy’ Venezuela has officially retaken its diplomatic headquarters in Washington, DC, after the properties were under US State Department control since 2023. Officials re-hoisted the national flag and announced a rehabilitation process to restore full consular services for Venezuelan nationals. The development follows renewed diplomatic ties between Caracas and Washington and a US sanctions waiver permitting operations of Venezuelan missions. Authorities say the facilities will address passport processing, legal documentation, and citizen assistance after years of restricted access. Read the full report here 👉🏾https://venezuelanalysis.com/news/venezuela-reclaims-us-diplomatic-venues-as-rodriguez-promotes-faith-diplomacy/ #diplomacy#Religion#USVenezuelaRelations

123•••10•••20•••2324
ПретходнаСтраница 1 од 24Следна