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

Резултати

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

Пребарај: #referrals

当前筛选 #referrals清除筛选
BLC Market - mini-app BulCoin

@bulcoin_blc · Post #338 · 16.04.2026 г., 10:00

Now is the best time to enter BLC Market. Early stage project: - actively forming structure - interfaces are being published - new mechanics are opening up If you're already here - you're getting in ahead of most. Scaling will follow next. #community#referrals FAQ | BUY

🏆 Premium, NFT, Tokens

@Giiveaways · Post #2171 · 18.06.2024 г., 16:00

👥 The system of inviting friends to CITY Holder! 🏠🐹 With the invitation system you get in-game income not only for inviting friends, but also for their further development! The better your buddy's results, the higher your income. Combine strategies and show incredible results! #CITYHolder#Referrals https://t.me/cityholder🆕👈 °°°°°°

BLC Market - mini-app BulCoin

@bulcoin_blc · Post #278 · 07.03.2026 г., 12:00

Launching the BulCoin Referral Program We are starting a referral program for the early BulCoin community. Now every participant can invite friends to the project and receive additional bonuses. How it works: Invite your friends to the BulCoin channel Ask them to mention your username in the comments to this post Bonuses BLC are credited for invitations Rewards: • 3 invited — You join the private Pioneers chat • 10 invited — Bonus of 500,000 BLC • 25 invited — 3mln BLC + Participation in the BulCoin operational staff We will regularly publish the leaderboard — participants who have invited the most people. The best participants can receive additional rewards and a special status in the community. This is just the beginning of the formation of the BulCoin Early Community Invite your friends and help build the BulCoin community #Pioneers#Referrals FAQ | BUY

BLC Market - mini-app BulCoin

@bulcoin_blc · Post #336 · 12.04.2026 г., 10:00

Invitation mechanics in BLC Market There will be a separate section in the app through which you can invite new users. This will allow: — community to grow faster — build connections between members — increase activity within the platform We will show the interface in the upcoming updates. #profile#community#referrals FAQ | BUY

SingSing Announcement

@singsingchannel · Post #935 · 27.10.2024 г., 06:52

🎉 Invite Reward Boost! 🎉 Invite friends to join SingSing and earn 20 $KARA FREE for each successful invite (up from 10 $KARA)! 🔥 👥 The more, the merrier – stack up your $KARA effortlessly! 💸 Start inviting now and claim your rewards! #SingSing#KARA#Invite#Referrals 🎤Announcement | Chat | X (Twitter) | Website | Game