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

Резултати

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

Пребарај: #devblog

当前筛选 #devblog清除筛选
DeckForge Announcement

@deckforge_official · Post #233 · 05.05.2025 г., 08:21

Yama again Last time we talked about what matters to you And today I want to share something that matters to us, developers Soo... 🚂 MEET THE ENGINE 🚂 Choosing an engine for our ambitious game was a challenge DeckForge will eventually be available on many platforms and devices That means that our code has to be easily maintainable, configurable and expandable for different environments We considered several possible solutions, including major game engines We prioritized fast loading, flexibility and cool graphics And after careful evaluation we ended up crafting our own solution on top of the good old three.js library 🤘👵🏻🤘 In terms of rendering - the game is an intricate sandwich of three.js scene wrapped with several layers of html The fun part - three.js is a 3D library with gpu shaders and stuff This enables a lot of visual tools, like VFX and camera shakes Oh, we will make her pretty ✨ Brace yourself, next time i will tell you everything about shaders (👁ˋ _ ˊ 👁) #DeckForge#DevBlog Join the DeckForge Community: 🌐YouTube𝕏Twitter🎮Discord 👉Chat👉Announcements

DeckForge Announcement

@deckforge_official · Post #220 · 20.04.2025 г., 14:08

Hello, future Deck Lords I am Yama - Game Director at DeckForge I represent team LAB behind the development process LAB is a dream team of veterans from different branches of gaming industry and we are very passionate about the game We want to share with you, our players, cool stuff about the development process, listen to your feedback and craft a universe for all of us to enjoy Let's start with some basics 🔵this will be an actual game with gameplay and everything \0/ 🔵we have already produced the alpha version and are moving fast towards beta 🔵multi-platform game, baby! Why are we doing this 🔵we believe the time has come to create a real game product for web3 community 🔵we believe our players want everything a good game should have: gameplay, meta, competitiveness 🔵we believe that we can bring together web3 and web2 communities for their mutual benefit Stay tuned The Forge has just been lit 🔥 #DeckForge#DevBlog Join the DeckForge Community: 🌐YouTube𝕏Twitter 👉Chat👉Announcements

DeckForge Announcement

@deckforge_official · Post #230 · 28.04.2025 г., 14:17

Hello gents Yama here 0/ Let's talk Founder Packs We want you to have fun and profit So we came up with a plan Founder Pack Tiers 🔵 there will be several tiers of Founder Packs (we think 5 is good) 🔵 everyone will be able to claim the lowest tier 🔵 $BOOMS holders - we feel you - depending on your account balance and activity you will be able to claim higher tiers What is inside? 🔵 resources and currency to boost your progress 🔵 powerful items that will give you the edge over competitors 🔵 unique cards and customizations that will not be available through other means 🔵 chance to grab precious NFTs and prizes from our partners Stay tuned for more details #DeckForge#DevBlog#FoundersPack ⸻ Join the DeckForge Community: 🌐YouTube𝕏Twitter 👉Chat👉Announcements