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

Резултати

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

Пребарај: #devcon2024

当前筛选 #devcon2024清除筛选
BNB Chain

@BNBCHAIN · Post #3972 · 13.11.2024 г., 08:41

Save on your rides during #DevCon2024! 🚕 Get your first ride free & 50% off after your free ride by using $USDT, $FDUSD or $USDC on BNB Chain by using the TADA mini app!

Hashtags

DWF Labs Broadcast

@DWFLabs · Post #965 · 18.11.2024 г., 10:27

DWF Ventures had a great time at #Devcon2024. Keep reading to get an overview on some key takeaways from their team 👇 Market sentiment is shifting positively as the results of the U.S. Election have resulted in increased confidence in the crypto market. Projects are in a good place to enjoy better price discovery after $BTC hit an all time high. Altcoins and memecoins are both vying for retail trading liquidity, and the rise of memecoins showcases a more community-driven crypto cycle coming. #Devcon2024 was a sign of increased crypto activity in Bangkok, and some main narratives were DeSci, AI agents, DeFi, and memes, with a new Ethereum proposal mentioned at the conference as well. To read the full recap, click here: https://x.com/DWFVentures/status/1858445960374084049 The team at DWF Ventures is looking to invest in innovative projects — if you are building, reach out to their team at dwf-labs.com/ventures🤝

Hashtags

DWF Labs Broadcast

@DWFLabs · Post #959 · 14.11.2024 г., 07:32

Excited to be one of the cohosts alongside Cypher Capital, 1inch, and Kava Chain at #Devcon2024🔥 Lingling Jiang, the Partner of DWF Labs, shared more on what's ahead for DWF Labs at this meet up 🙌 Thank you to everyone who came to the event. We look forward to seeing you at our next event ✨️

Hashtags

DWF Labs Broadcast

@DWFLabs · Post #958 · 13.11.2024 г., 02:52

Happening tomorrow at 1:15PM GMT+7 — Lingling Jiang, Partner of DWF Labs, will be sharing insights about what's coming up in DWF Labs' journey 🔥 Register for the event "Bridging Worlds: DeFi & VC Innovation Meetup" to listen to her speech: https://lu.ma/CypherCapital1inchDWFLabsKAVA We're excited to be hosting alongside Cypher Capital, 1inch, and Kava Chain during #Devcon2024. See you there!

Hashtags

DWF Labs Broadcast

@DWFLabs · Post #956 · 12.11.2024 г., 04:35

During Korea Blockchain Week in September, Lingling Jiang, Partner of DWF Labs, shared about our vision and what's coming in the future. This week, she'll be sharing more insights about our journey and initiatives during the event "Bridging Worlds: DeFi & VC Innovation Meetup" at #Devcon2024🔥 We are co-hosting the event alongside Cypher Capital, 1inch, and Kava Chain🤝 Register here: https://lu.ma/CypherCapital1inchDWFLabsKAVA

Hashtags

DWF Labs Broadcast

@DWFLabs · Post #955 · 12.11.2024 г., 01:15

GM Bangkok! 🇹🇭 Our team is excited for #Devcon2024, and we are looking forward to connecting with you this week. Make sure to say hello when you spot us — we're thrilled to meet you all 🔥

Hashtags