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

Резултати

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

Пребарај: #tensions

当前筛选 #tensions清除筛选
Crypto M - Crypto News

@CryptoM · Post #65353 · 13.04.2026 г., 02:04

🚀 Iranian Official Warns of Potential Response to U.S. Naval Blockade An Iranian official has issued a warning regarding Iran's potential response to a U.S. naval blockade. According to NS3.AI, the official indicated that Iran possesses an unused strategy that could be employed if tensions escalate further. This statement comes amid ongoing geopolitical tensions between the two nations, highlighting the complex dynamics at play in the region. #Iran#US#NavalBlockade#Geopolitics#Tensions#Strategy#MiddleEast

Crypto M - Crypto News

@CryptoM · Post #65095 · 11.04.2026 г., 00:45

🚀 Lebanon and Israel to Hold First Meeting on Ceasefire Talks Lebanon and Israel have agreed to hold their first meeting on Tuesday at the U.S. State Department to discuss a ceasefire and set a date for negotiations. According to BlockBeats, this development marks a significant step towards addressing ongoing tensions between the two nations. #Lebanon#Israel#Ceasefire#Negotiations#USStateDepartment#Tensions

Crypto M - Crypto News

@CryptoM · Post #65350 · 13.04.2026 г., 01:55

🚀 U.S. and Iran Maintain Temporary Ceasefire Amid Tensions U.S. President Donald Trump announced that the temporary two-week ceasefire between the United States and Iran is "generally holding well." According to Odaily, this statement comes despite the lack of progress in marathon negotiations held over the weekend in Pakistan. Trump, speaking to reporters upon his return to Washington from Florida, stated, "I think it's generally holding well. Their military has been destroyed. Their entire navy is at the bottom of the sea." He also mentioned that the U.S. would begin a blockade of the Strait of Hormuz at 10 a.m. Eastern Time on Monday. Additionally, Trump noted that two American soldiers rescued in Iran earlier this month are currently in good condition. #US#Iran#Ceasefire#Tensions#Trump#Military#Negotiations#StraitOfHormuz

Crypto M - Crypto News

@CryptoM · Post #65018 · 10.04.2026 г., 14:06

🚀 Iranian Military Maintains High Alert Amid U.S. and Israeli Tensions On April 10, the Iranian Armed Forces announced that they remain on high alert, ready to engage if necessary. According to BlockBeats, a spokesperson from the Khatam al-Anbiya Central Headquarters stated that this stance is due to repeated breaches of trust by the United States and Israel. The statement underscores ongoing tensions in the region, highlighting Iran's preparedness to respond to perceived threats. #Iran#Military#US#Israel#Tensions#MiddleEast#Alert

Crypto M - Crypto News

@CryptoM · Post #65401 · 13.04.2026 г., 05:15

🚀 U.S. to Impose Blockade on Iranian Ports Amid Tensions U.S. President Donald Trump announced on his social media platform that the United States will enforce a blockade on ships entering and exiting Iranian ports at 10 a.m. Eastern Time on April 13. According to BlockBeats, this decision follows unsuccessful negotiations between the United States and Iran. On April 12, President Trump expressed indifference towards Iran's willingness to return to the negotiating table. He reiterated the plan to impose the blockade and voiced disappointment over NATO's lack of support for the U.S. in the conflict involving Iran. #US#Iran#blockade#Trump#NATO#tensions#MiddleEast#sanctions#diplomacy

Crypto M - Crypto News

@CryptoM · Post #65141 · 11.04.2026 г., 11:36

🚀 Russia and Ukraine Conduct Prisoner Swap Mediated by UAE Russia and Ukraine have successfully exchanged 175 prisoners of war, with the United Arab Emirates playing a mediating role in the process. Bloomberg posted on X, highlighting the significance of this exchange amid ongoing tensions between the two nations. The swap marks a notable development in the efforts to address humanitarian concerns arising from the conflict. Both countries have been engaged in a prolonged conflict, and such exchanges are seen as steps towards easing tensions and addressing the humanitarian impact of the war. The involvement of the UAE underscores the international community's interest in facilitating dialogue and resolution between Russia and Ukraine. This exchange is part of ongoing efforts to manage the humanitarian aspects of the conflict, which has drawn widespread international attention. #Russia#Ukraine#PrisonerSwap#UAE#HumanitarianEfforts#ConflictResolution#InternationalDiplomacy#HumanitarianImpact#Tensions#War