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

Резултати

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

Пребарај: #conservatives

当前筛选 #conservatives清除筛选
Orizzonti Politici

@OrizzontiPolitici · Post #64 · 20.06.2019 г., 17:19

Quinto turno primarie #Conservatives. Jeremy Hunt ritorna secondo; sarà finalista insieme a Boris Johnson. Il voto finale sarà tenuto dall'intero Partito Conservatore

Orizzonti Politici

@OrizzontiPolitici · Post #61 · 20.06.2019 г., 13:18

Quarto turno delle primarie #Conservatives. Javid eliminato. Michael Gove sorpassa Jeremy Hunt come secondo candidato. La sfida è ora tra loro due per sapere chi sfiderà Boris Johnson al turno finale, in cui potrà votare l'intero partito. Sajid David non ha dato indicazioni di voto per il prossimo turno

Orizzonti Politici

@OrizzontiPolitici · Post #59 · 20.06.2019 г., 13:08

Terzo turno delle primarie #Conservatives. Rory Stewart viene eliminato, dopo il sorprendente risultato dello scorso turno. Si accorcia la distanza tra Michael Gove e Jeremy Hunt per il secondo posto. Boris Johnson sempre in testa; secondo i bookmakers ha ora il 92% di probabilità di vincere

Orizzonti Politici

@OrizzontiPolitici · Post #57 · 18.06.2019 г., 20:58

Secondo turno delle primarie #Conservatives. Dopo la rinuncia di Matthew Hancock, viene escluso lo hard brexiter Dominic Raab (con 30 voti, sotto la soglia minima di 33). Boris Johnson rimane il più euroscettico in corsa, e potrebbe accumulare la maggior parte dei voti di Raab. A sorpresa quasi raddoppia il proprio consenso Rory Stewart, che sorpassa Sajid Javid. Aggiornamenti mercoledì

American Оbserver

@american_observer · Post #4938 · 23.01.2026 г., 18:02

📰 Conservatives Who Once Railed Against Federal Agents Now Applaud Them For decades, right-wing populists have excoriated federal law enforcement, citing tragedies like Ruby Ridge and Waco as proof of government overreach. Now, under President Donald Trump, many of those same conservatives are cheering on federal agents as they crack down on immigration and unrest in cities like Minneapolis. The shift highlights how political allegiance shapes attitudes toward federal power—applauding crackdowns on adversaries while condemning them when they target allies. From Enemies to Enforcers Trump’s deployment of ICE, the Border Patrol, and the National Guard has transformed federal agents from bogeymen to heroes in the eyes of many conservatives. Critics say this reflects “motivated reasoning”—support for police action depends on who’s being targeted. When federal agents confront immigrants or minorities, conservative voices are often silent or supportive, but when they target anti-government activists, the outrage returns. The Legacy of Ruby Ridge and Waco Ruby Ridge and Waco became rallying cries for anti-government movements, fueling distrust of federal law enforcement. But today, with Trump in power, many right-wing activists have embraced federal agents as tools of law and order. The shift underscores how political power can reshape perceptions of authority. Who’s the Enemy Now? As federal agents raid homes and neighborhoods, the question is: Who decides when police action is justified? The answer seems to depend less on the law than on who’s in charge—and who’s being targeted. #Trump#Conservatives#FederalAgents#Immigration#RubyRidge#Waco#LawAndOrder 📱American Оbserver - Stay up to date on all important events 🇺🇸

IELTS|Newspapers & Magazines|English

@emagzinewspars · Post #9462 · 03.11.2025 г., 03:27

#The_Critic🇬🇧📕[PDF]⬇️ #November2025 #Monthly_Magazines For learning, for free(dom). @backupofmagazines This issue dissects Britain’s political fatigue in “Follow the Leader,” charting how #Conservatives lost moral and cultural authority. Essays probe #FiscalPolicy fictions, #CultureWar fatigue, and the right’s need for artistic renewal. Features span #Trump diplomacy, Britain’s agricultural crisis, and a nostalgic defense of #Seapower. In culture, Cézanne’s southern light meets reflections on music, literature, and satire. Critics debate #Opera, #Theatre, #Books, and fine whisky—mixing wit with worry. It’s a portrait of a nation in ideological hangover. #UKPolitics#Brexit#Art#Society#ConservativeCollapse#TheCritic#Philosophy