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

Резултати

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

Пребарај: #uncertainty

当前筛选 #uncertainty清除筛选
IELTS|Newspapers & Magazines|English

@emagzinewspars · Post #9736 · 18.12.2025 г., 15:35

#MIT_Sloan_Management_Review🇺🇸📕[PDF]⬇️ #Winter2026 #Monthly_Magazines For learning, for free(dom). @backupofmagazines This issue explores how leaders can turn volatility into advantage by treating #Uncertainty not as a threat but as a strategic resource. The issue’s cover package on #StrategicForesight shows how scenario planning, analogical thinking, and long-term perspective help organizations navigate an #AI-driven world. Essays on #AuthenticLeadership question whether “being yourself” builds trust or excuses bad behavior, while deep dives into #AlgorithmicPricing and #ResponsibleAI highlight rising legal and ethical risks. Across strategy, innovation, and #Sustainability, the message is clear: progress comes from disciplined adaptation, not endless upheaval.

Crypto M - Crypto News

@CryptoM · Post #65043 · 10.04.2026 г., 15:45

🚀 U.S. Prepares Military Response Amid Iran Peace Talks, Says Trump U.S. President Donald Trump has stated that if peace negotiations with Iran fail, American warships are being equipped with advanced ammunition to resume strikes. According to Odaily, Trump's comments came shortly before U.S. Vice President Vance boarded Air Force Two en route to Islamabad for peace talks with Witkoff and Kushner. In a phone interview, Trump expressed uncertainty about the success of the negotiations, saying, "We will know in about 24 hours. We are rearming our ships with the finest ammunition and the most advanced weapons, even better than what we used before, which had already defeated them. If no agreement is reached, we will use them very effectively." Trump further commented on the unpredictability of the situation, stating, "We are dealing with people whose honesty is uncertain. They claim to abandon all nuclear weapons in front of us, but then tell the media they want to enrich uranium. We will find out the truth." #US#Trump#Iran#MilitaryResponse#PeaceTalks#Ammunition#Warships#NuclearWeapons#Uncertainty#Diplomacy#Pakistan#AirForceTwo

Crypto M - Crypto News

@CryptoM · Post #64734 · 09.04.2026 г., 16:31

🚀 Uncertainty Surrounds Trump's Attendance at Mar-a-Lago Gala Terms for the April 25 official gala at Mar-a-Lago indicate that U.S. President Donald Trump may not be able to attend, and organizers reserve the right to reschedule or cancel the event. According to NS3.AI, a spokesperson from Get Trump Memes stated that Trump is still anticipated to attend both the Florida luncheon and the White House Correspondents' Dinner in Washington that evening. #Trump#MarALago#gala#uncertainty#attendance#reschedule#cancel#floridaluncheon#whitehousecorrespondentsdinner#NS3AI#GetTrumpMemes