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

Резултати

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

Пребарај: #slexlaunchpad

当前筛选 #slexlaunchpad清除筛选
SLEX NEWS

@slex_io · Post #159 · 16.02.2024 г., 10:20

🚀 Great Start of SLEX Launchpad!🎉 ⚡️The first day of SLEX Launchpad sales was a huge success with over 37,78% of allocations sold out! Whitelist participants, you have a last chance to be part of this exclusive event, but hurry up as allocation actively decreases with high users demand📈 🗓️The sale ends tomorrow, February 17th. Don't miss the last chance to take exclusive advantages of SLEX Launchpad. #SLEXLaunchpad#LastChance#CryptoSale Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter

SLEX NEWS

@slex_io · Post #161 · 18.02.2024 г., 08:32

🎉Amazing Success of the first SLEX Launchpad! 🚀 📈A huge thanks to all participants who joined the first SLEX Launchpad! Your participation made it an outstanding success! 🔥 🤝Don't miss out on future opportunities - follow us on our social channels. Here's you can find more interesting updates and events soon: Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter #SLEXLaunchpad#SLEX#SLEXSale#StayTuned

SLEX NEWS

@slex_io · Post #158 · 15.02.2024 г., 06:52

🚀The Time Is UP: Today is the First Day of SLEX Launchpad Sale! ☄️ ⚡️The wait is over! The first SLEX Launchpad officially starts today, February 15th at 12:00 UTC, after our Whitelist successfully closed with over 4000 participants. This marks the beginning of exceptional earning opportunities for our community🎉 🔥Premier Project Access: SLEX token holders, get ready for exclusive access to Tier-1 crypto projects. These handpicked projects offer a rare chance to invest in potentially profitable tokens. 💰Maximize Your Earnings: participate in the Launchpad to unlock staking rewards and additional trading benefits on SLEX Exchange. 📅 Important Reminder for Whitelist Members: 👀Due to the fact that token allocation and the time of the sale are limited, we recommend to deposit funds on your account in advance. ✍🏻If you did not create an account on SLEX yet, make sure that you create one under the email you specified in the Whitelist application form to be able to participate in token sale. #SLEX#LaunchpadLive#SLEXTokens#SLEXLaunchpad#SLEXWhitelist Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter

SLEX NEWS

@slex_io · Post #155 · 13.02.2024 г., 14:27

🚀Let the Sale Begin: The first SLEX Launchpad for 4000 Participants Starts on February 15th! 🎉 ⚡️We are thrilled to announce that the Whitelist on SLEX has been successfully closed with more than 4000 participants. And now we are at the finish line because it's only two days until the launch of the much-anticipated SLEX Launchpad!⚡️ 📈Mark your calendars and prepare to join SLEX Launchpad to get access to exceptional ways of earning: 🔥Access to Tier-1 Projects: SLEX token holders will gain exclusive access to Tier-1 projects, offering a gateway to the most promising and innovative crypto projects. 💰Staking Rewards and Trading Benefits: Token holders can get rewards from staking and additional trading bonuses at SLEX Exchange. 📅 If you are a Whitelist member check out email for more details and instructions about participation in the first SLEX Launchpad! #SLEX#LaunchpadAnnouncement#CryptoInnovation#SLEXTokens#TradingBenefits#SLEXLaunchpad#SLEXWhitelist Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter

SLEX NEWS

@slex_io · Post #149 · 24.01.2024 г., 16:32

🚨 Last Chance: SLEX Whitelist is Coming to an End! ⏳ 🔥Time is ticking! The exclusive opportunity to join the SLEX Whitelist only for the community is nearing its end on February 1st. This is an exceptional way to get early access to a limited allocation of SLEX Coins before Public listing! 🤝Take your last chance and join SLEX Whitelist: slex.io/launchpad/slex 🤔We've also got an exciting way to show you the ambitious and in-depth look at SLEX plans and vision on Binance:www.binance.com/en-AE/feed/post/1058789 #SLEXWhitelist#SLEXExchange#JoinNow#BinanceArticle#SLEXCoin#PublicSale#SLEXLaunchpad Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter