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 слични објави

Пребарај: #ocro

当前筛选 #ocro清除筛选

🚀 OCRO IEO: Built to Rise, Designed to Reward IEOs are changing the game—and Octario Exchange is leading the way with OCRO. Unlike traditional ICOs, the OCRO IEO is hosted directly on the exchange, offering trust, transparency, and real structure. Powered by the Rising Edge Mechanism, OCRO’s price increases across 3 phases: from $0.30 to $0.80, before launching at $1.00. 📈 Each phase = limited supply + higher price 🎯 Early buyers = best value + built-in scarcity OCRO holders also get real utility: low gas fees, access to blockchain games, and real-world asset exposure. Don’t miss this rare chance to join a token economy engineered to grow. 👉 Participate now at 📢 Let’s talk about the Rising Edge Mechanism that makes OCRO unique: 📈 Upward-Only Pricing You can’t sell OCRO for less than your purchase price. Every sale must occur higher than the last. 🔓 Demand-Driven Supply Every buy unlocks more tokens from escrow, fueling circulation only when there is real demand. ⚡️ Momentum Over Volatility Instead of price drops, market activity creates upward pressure. The more people participate, the stronger OCRO becomes. 💠 This makes OCRO the first token designed to rise by design. 👉octario.exchange #OCRO#IEO#CryptoLaunch#OctarioExchange#BuiltToRise

INK GAME — OFFICIAL TEASER JUST DROPPED! Inspired by Squid Game. Dark. Intense. Only for the brave. 🎮🔥 The countdown has begun… 13 January 2026 — the arena opens. Only 456 players will step inside. Only the worthy will compete. 🔻 QUALIFICATION TO ENTER THE 456 🟥 20,000 USDT Direct Sales OR 🟥 10,000 USDT Self-Purchase (OCRO Phase 2) This isn’t just a launch event — it’s a selection. ⚡ Massive rewards. ⚡ One arena. ⚡ Choose your faction… and survive. #INKGame#Octario#OCRO#SquidGameStyle#456PlayersOnly

🚀 Top news! 🚀 We are launching the OCRO token with guaranteed growth - the price will rise from $0.02 to $0.10 in just 90 days from June 6th! 💥 And the best part: register with our exclusive link NOW and get a $50 gift as a thank you! 🎁 🔗 *https://octario.exchange/login/register?InvitationCode=833700* Join the future of crypto with guaranteed growth and cool bonuses! Don't miss your chance - join today! 🚀✨ #Crypto#TokenLaunch#OCRO#GuaranteedGrowth#Investments#CryptoCommunity#IEO