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

Резултати

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

Пребарај: #america

当前筛选 #america清除筛选
RTDocumentary

@rtdocumentary · Post #697 · 03.05.2022 г., 13:59

#video#America In 1986, a two-year-old girl died in a fire in the United States. Her mother's former roommate was accused of arson and imprisoned on death row. But some of the evidence turned out to be fake, and the prosecution witnesses refused to testify. Finally, after 21 years, the court recognised the verdict was a mistake and released him. The film Imprisoned: The Man with a Cigarette is one of the episodes of the RT Documentary series about mistakes in American justice. Follow: https://t.me/rtdocumentary

Suriyakmaps

@suriyak_maps · Post #9681 · 11.03.2026 г., 15:36

The conflict between #Iran and #America is unconventional How Iran is conducting the war and the nature of its military operations. The impact of this conflict on the region and the world. video link (Dubbed):https://youtu.be/egZ_KHA2pW8?si=iUJw2x3lLoyGFbgO

Islamic World News

@iswnews_en · Post #17305 · 12.03.2026 г., 01:58

🇮🇷/🇺🇸🇦🇪🔥Iran's missile/drone attack on US army positions and interests in Dubai. Tonight, the UAE and the city of Dubai witnessed several retaliatory attacks by Iran. #Iran#America#UAE

RTDocumentary

@rtdocumentary · Post #780 · 17.05.2022 г., 13:59

‘I am a black gay immigrant woman ... to hold this position’. So the new White House Press Secretary decided to talk about just that at her first briefing. Karine Jean-Pierre is 44 years old, and she raises a daughter with her lesbian partner. She has an ideal profile for the US Democratic Party: Jean-Pierre is an African American with Haitian roots, a representative of the LGBT community who studied at the prestigious Columbia University. Karine Jean-Pierre replaced Jen Psaki as US President’s spokeswoman. Previously Karine stood behind the podium only when Psaki was ill or on vacation. Now, this is who we’ll learn about the administration’s policy direction and possible further sanctions against Russia. But do sanctions have a strong bite? Watch the film Sanctions: Opportunity in Disguise. #WhiteHouse#America Follow: https://t.me/rtdocumentary

Papa & Vaticano - News

@papaevaticanonews · Post #9571 · 06.03.2026 г., 15:17

Il 9 e 10 marzo, nella suggestiva cornice dei giardini papali di #CastelGandolfo, prenderà il via la Global Alliance, un’iniziativa internazionale dedicata all’ecologia integrale e alla sostenibilità globale, promossa dal Centro di Alta Formazione Laudato si’ e dall'Università di Notre Dame. All’evento inaugurale parteciperanno rappresentanti di oltre sessanta università di #Europa, #Asia, #America e #Africa, ed esponenti delle principali organizzazioni internazionali impegnate nella lotta alla crisi climatica. Due giorni di confronto, riflessione e scambio di esperienze per costruire un approccio integrato alla sostenibilità, basato sui principi dell’Enciclica Laudato si’ e della Dottrina Sociale della Chiesa. La Global Alliance nasce con l’obiettivo di connettere università, centri di ricerca, comunità e istituzioni impegnate nella promozione di pratiche sostenibili, valorizzando le sinergie tra ricerca, educazione e azione comunitaria. La rete intende creare un’infrastruttura condivisa capace di amplificare l’impatto globale dell’ecologia integrale, unendo fede, scienza e giustizia sociale, per contrastare così degrado ambientale, disuguaglianze e ingiustizie ecologiche. Tra i risultati attesi: la costituzione di una rete globale di istituzioni, la creazione di gruppi tematici per lo sviluppo di agende di ricerca e strumenti formativi, e il rafforzamento della visibilità e del contributo cattolico nel dibattito internazionale sulla sostenibilità. Il Cardinal Fabio Baggio, Direttore Generale del Centro di Alta Formazione Laudato si’ e tra gli ideatori della Global Alliance, sottolinea: "La Global Alliance nasce come un cammino condiviso di speranza: unire scienza, comunità e fede per custodire il creato, proteggere i più fragili e costruire insieme un futuro sostenibile, giusto e rispettoso di ogni persona". "Notre Dame è profondamente impegnata nella visione morale della Laudato Si’, per salvaguardare coloro che si trovano ai margini e prendersi cura della nostra casa comune - dichiara il Presidente dell’Università, Robert A. Dowd, C.S.C. -. Siamo onorati di collaborare con il Vaticano in questa Alleanza Globale, che riunirà illustri leader e ricercatori nel campo della sostenibilità e dell’ecologia integrale provenienti da tutto il mondo, per creare un futuro più giusto e resiliente per tutti". La Global Alliance rappresenta così una rete strategica di speranza, capace di tradurre l’impegno per l’ecologia integrale in progetti concreti e duraturi a livello globale.

Addis Standard

@addisstandardeng · Post #21690 · 12.03.2026 г., 11:04

#Op_ed: Aggression as Norm: How #America’s triad of hegemony destabilizes global order, redefines sovereignty In this op-ed, Hassen Mama Muse contends that the February 2026 strikes on #Iran and the arrest of Nicolás Maduro signal a new era where “the immediate security and economic imperatives of the American unipole override established global norms.” He views this as the culmination of a century long strategy of U.S. primacy exerted through diplomacy, military force, and covert influence. Beyond power projection, #Washington uses “weaponized interdependence”—leveraging economic and financial networks to shape peripheral states. To counter this, Hassen urges the Global South to pursue a “Multiplex World” focused on economic autonomy and “Decentred Globalism,” prioritizing regional hubs and horizontal partnerships instead of superpower dominance. https://addisstandard.com/?p=55782

Addis Standard

@addisstandardeng · Post #21292 · 03.02.2026 г., 11:02

#Commentary: From Internal Unity to Strategic Diplomacy: #Ethiopia’s playbook for dealing with Trump’s #America In this commentary, Teferi Tafa examines how the Trump administration’s renewed engagement over the Grand Ethiopian Renaissance Dam (#GERD) and Nile water disputes has intensified Ethiopia’s strategic challenges. He notes that “Ethiopia faces a critical moment that demands not just reactive diplomacy but a comprehensive strategy rooted in internal cohesion and enhanced bargaining power.” Highlighting internal division and conflicts as the greatest vulnerability, Teferi states, “No amount of diplomatic maneuvering can compensate for a house divided against itself.” He concludes, “Ethiopia’s response to this diplomatic moment will define not just its relationship with the Trump administration but also its trajectory for the coming decade.” https://addisstandard.com/?p=54948

Suriyakmaps

@suriyak_maps · Post #10145 · 24.03.2026 г., 00:05

The escalation continues… and #Iran denies any negotiations with #America. Missile strikes and underground bases remain operational despite the bombing. The #Yazd base becomes a military enigma, baffling everyone. And the #Lebanon front… video link (Subtitled):https://youtu.be/DOebjiVJxlU?si=24HNJ2m9osQy8a4L

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