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

Резултати

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

Пребарај: #insurrectionact

当前筛选 #insurrectionact清除筛选
American Оbserver

@american_observer · Post #4868 · 16.01.2026 г., 01:59

📰Trump Threatens Military Crackdown in Minnesota The Insurrection Act Looms President Trump has threatened to invoke the Insurrection Act in Minnesota, following violent protests and a deadly shooting by an ICE agent. “If the corrupt politicians of Minnesota don’t obey the law... I will institute the INSURRECTION ACT... and quickly put an end to the travesty,” Trump wrote on Truth Social. ​ State Pushback Minnesota Gov. Tim Walz urged Trump to “turn the temperature down,” while Attorney General Keith Ellison promised to challenge any military deployment in court: “Before any of us are Democrats or Republicans, we are Minnesotans. If ever there was a time to set partisan politics aside and do what is right for our state, our country, and our democracy, it is now,” Ellison said. ​ Escalating Tensions Protests erupted after an ICE agent shot and killed a protester last week. Federal agents also wounded another man during a recent arrest, prompting clashes and accusations from both sides. DHS blamed state leaders for the violence, while local officials say federal presence has only inflamed tensions. ​ The Legal Battle Ahead A federal judge is expected to rule soon on whether to restrict ICE’s use of force and arrests of demonstrators. Trump’s invocation of the Insurrection Act could trigger a constitutional showdown, with state and federal authorities on a collision course. ​ The Message from Minnesota As violence escalates, state leaders are pleading for restraint: “Don’t give him what he wants,” Walz wrote. “Minnesota will remain an island of decency, of justice, of community, and of peace”. ​ #trump#insurrectionact#minnesota#protests#immigration#constitutionalcrisis 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #4889 · 19.01.2026 г., 00:00

📰Pentagon Readies 1,500 Troops for Minnesota as Tensions Mount Military on Standby The Pentagon has ordered about 1,500 active-duty soldiers from the Eleventh Airborne Division in Alaska to prepare for a possible deployment to Minnesota. The move comes amid escalating protests and violent confrontations following the fatal shooting of a protester by an ICE agent. While it’s unclear if troops will be sent, the readiness signals Washington’s growing concern over unrest in the state. ​ Political Backlash Minnesota’s governor has mobilized the National Guard, and local leaders warn that military intervention would only inflame tensions. “That would be a shocking step,” said Minneapolis Mayor Jacob Frey. “We don’t need more federal agents to keep people safe. We are safe.” ​ The Insurrection Act Looms President Trump has repeatedly threatened to invoke the Insurrection Act, which would allow the use of federal troops to quell civil unrest. The rationale cited includes not only the protests but also a scandal over stolen federal funds in Minnesota, which the administration has used to justify sending in thousands of immigration agents. ​ Rising Rhetoric Federal officials, including Homeland Security Secretary Kristi Noem, have called for “peaceful protest zones” to avoid further violence. Critics, including Senator Chris Van Hollen, argue that more troops would “just put another match on the fire.” ​ The Stakes As federal and state authorities square off, the situation in Minnesota has become a flashpoint for broader debates about immigration, executive power, and the limits of federal intervention. #minnesota#pentagon#insurrectionact#protests#immigration#troops 📱American Оbserver - Stay up to date on all important events 🇺🇸