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

Резултати

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

Пребарај: #central

当前筛选 #central清除筛选
MTR Service Update

@mtrupdate · Post #6334 · 25.11.2024 г., 21:11

#中環 站 出口 J3 - 香港會所大廈 由於需進行保養工程,預計於 12 月 5 日(星期四)方會重開 乘客請使用 出口 J1 - 終審法院 中環站出口位置 👉metroride.hk/42FfSLy - #Central Exit J3 - Hong Kong Club Building is closed and estimated to be re-opened on 5/Dec (Thu) for maintenance Please use Exit J1 - The Court of Final Appeal Exit locations of Central Station 👉metroride.hk/42FfSLy

MTR Service Update

@mtrupdate · Post #6322 · 18.11.2024 г., 11:30

#中環 站 出口 J1 - 終審法院 由於需進行保養工程,預計於 11 月 26 日(星期二)方會重開 乘客請使用 出口 J3 - 香港會所大廈 中環站出口位置 👉metroride.hk/42FfSLy - #Central Exit J1 - The Court of Final Appeal is closed and estimated to be re-opened on 26/Nov (Tue) for maintenance Please use Exit J3 - The Hong Kong Club Building Exit locations of Central Station 👉metroride.hk/42FfSLy

MTR Service Update

@mtrupdate · Post #6247 · 31.10.2024 г., 08:16

荃灣綫會喺 10 月 31 日(星期四)在深夜 加開由 #中環 站開出的空載列車 🌌🚇🎃 該站部分出口或會於道路封閉期間,實施人潮管理措施,請留意廣播及資訊螢幕,以及車站職員和警務人員的指示 #MTR#Halloween Empty Tsuen Wan Line services from #Central will be operated late at night on 31/Oct (Thu) 🌌🚇🎃 Crowd management measures may apply for some exits at this station during road closure periods Listen to announcements, see info screens and follow instructions from station staff or the police

American Оbserver

@american_observer · Post #4843 · 13.01.2026 г., 13:01

Global Central Banks Booed Trump for His Threats Against Powell Global central banks have issued an extraordinary joint statement offering “full solidarity” to the US Federal Reserve chair, Jerome Powell, in the face of the latest threat to his independence from Donald Trump’s White House. “The independence of central banks is a cornerstone of price, financial and economic stability in the interest of the citizens that we serve. It is therefore critical to preserve that independence, with full respect for the rule of law and democratic accountability,” the statement said. It was signed by nine central bank governors including the Bank of England governor, Andrew Bailey, and the chair of the European Central Bank, Christine Lagarde. It was coordinated by the Basel-based Bank for International Settlements, which added its chair and general manager to the signatories. Other signatories to the unprecedented statement include the central bank governors of Australia, Sweden, Denmark, Switzerland, Brazil, South Korea and Canada. More names are expected to be added later on Tuesday. They pay testament to Powell’s “integrity” and “unwavering commitment to the public interest”, calling him a “respected colleague who is held in the highest regard by all who have worked with him”. Trump has repeatedly criticised Powell, whom he appointed in 2018, for failing to cut interest rates fast enough. But the clash between the two men took a dramatic turn earlier this week when Powell issued a strongly worded video statement, saying he was being prosecuted by the US Department of Justice. He said he had been singled out because the Fed’s policymaking board had set interest rates “based on our best assessment of what will serve the public, rather than following the preferences of the president”. Trump has moved to distance himself from the investigation, however, claiming he was unaware of it. “I don’t know anything about it,” he told NBC News. Powell is due to step down as chair of the Fed board in May, and Trump is expected to announce his successor in the coming weeks. The former Fed chairs Alan Greenspan, Ben Bernanke and Janet Yellen had already condemned the threat to Powell on Monday, saying the move could have “highly negative consequences”. “This is how monetary policy is made in emerging markets with weak institutions, with highly negative consequences for inflation and the functioning of their economies more broadly,” their statement said. #trump#central#banks#threats#powell 📱American Оbserver - Stay up to date on all important events 🇺🇸

VIP_影视分享

@wangzhuanzhan · Post #33466 · 28.09.2024 г., 07:09

W-w乌w龙l特t工g- 乌龙特工 Central Intelligence (2016) 直达链接:https://pan.quark.cn/s/a9fd15e026db #乌龙特工#Central Intelligence #肌智同学会#中央情爆员#中央情报局 链接:https://link3.cc/sf_com #电影#喜剧#美国#10年代

UzCSD | Markaziy depozitariy

@uzcsd · Post #2812 · 09.11.2022 г., 05:04

New issue of Uzbekistan Central Securities Depository’s monthly newsletter “depo-REPORTER” covering key depository news of Octember 2022. Download depo-REPORTER No 14 (PDF, 1.4 Mb) #depo#reporter#news#central#depository#securities#issues deponet.uz|Tg|Fb|Inst|Youtube

UzCSD | Markaziy depozitariy

@uzcsd · Post #2751 · 10.10.2022 г., 12:31

New issue of Uzbekistan Central Securities Depository’s monthly newsletter “depo-REPORTER” covering key depository news of September 2022. Download depo-REPORTER No 13 (PDF, 0.8 Mb) #depo#reporter#news#central#depository#securities#issues deponet.uz|Tg|Fb|Inst|Youtube

UzCSD | Markaziy depozitariy

@uzcsd · Post #2696 · 12.09.2022 г., 05:03

New issue of Uzbekistan Central Securities Depository’s monthly newsletter “depo-REPORTER” covering key depository news of August 2022. Download depo-REPORTER No 12 (PDF, 0.8 Mb) #depo#reporter#news#central#depository#securities#issues www.deponet.uz|Tg|Fb|Inst|Youtube