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

Пребарај: #bcmctoken

当前筛选 #bcmctoken清除筛选
AIRDROPS BOSS

@airdropsboss · Post #852 · 25.12.2021 г., 13:59

To the beautiful and wonderful BeforeCoinMarketCap Community! Sincerest wishes for health, happiness, and peace during this Holidays season and throughout the coming year! We thank you all for your unlimited contribution. We hope you stay with us, there are many interesting things this coming year! Let the spirit of love gently fill our hearts and homes. In this loveliest of seasons may you find many reasons for happiness. From all of us at BeforeCoinMarketCap. 💝 #BCMC1#BeforeCoinMarketCap#Crypto#BCMCToken#Airdrop#Bounty

AIRDROPS BOSS

@airdropsboss · Post #853 · 28.12.2021 г., 13:42

Dear community! 💙 BCMC1 People IEO Airdrop⬇️⬇️⬇️ @bcmc_peopleIEO_airdropbot ✅ Please complete all the tasks and submit details correctly. 💰 Rewards: - If you complete all tasks you will get 450 BCMC1. 📊Market: CoinMarketCap 💧BOUNTY💧 ⏰ Airdrop will end on (UTC) or when there are 5,000 participants. #BCMC1#BeforeCoinMarketCap#BCMC#Crypto#BCMCToken#Airdrop

AIRDROPS BOSS

@airdropsboss · Post #830 · 15.11.2021 г., 14:59

🚀BeforeCoinMarketCap NEW AIRDROP🚀 💵Total Reward: 550 BCMC1 💰 Value: $8 📊Market: CoinMarketCap click here⤵️ 💎Airdrop Bot💎 ☝️Don't miss out on MLM (Ongoing tokens sale with limited pool). 🥳 Invite buyers with your referral links and earn 10% GOOD LUCK TO EVERYONE!!!✊🏻 💠Telegram 💠Telegram Channel 💠Twitter 💠Facebook 💠LinkedIn 💠YouTube 💠Website #BCMC1#BeforeCoinMarketCap#BCMC#Crypto#BCMCToken#Airdrop

AIRDROPS BOSS

@airdropsboss · Post #854 · 31.12.2021 г., 10:57

💧BeforeCoinMarketCap BOUNTY💧 (For 100 participants only💯) Make a video about our platform: Post it on your official YouTube channel (3-5 minutes) $50 - $100 in BCMC1 token. We take into account the length and quality of the content. Example: Please watch this videos for instructions: https://youtu.be/8t1ucZFnyL8 & https://youtu.be/aYrpgGpI074 1 Best video will receive 15,000BCMC1 ($200) and will posted on our social channels.🏆 Mandatory: ✅Describe the People IEO. (Community voting) ✅Describe the People IEO. (Participant projects) ✅Explain the MLM system (Ongoing token sales) ❗️Notice: The channel must have Minimum of 1000 subscribers. Your email will be blacklisted if you submit an old video link or if you do not follow the instructions given. #BCMC1#BeforeCoinMarketCap#BCMC#Crypto#BCMCToken#bounty#Bounty

AIRDROPS BOSS

@airdropsboss · Post #829 · 13.11.2021 г., 08:32

💎 BeforeCoinMarketCap New BOUNTY 💎 For 100 participants only💯 Bounty Tasks✅ Make a video about our platform: Post it on your official YouTube channel (3-5 minutes) $50 - $100 in BCMC1 token. We take into account the length and quality of the content. 📍Mandatory: 1. Describe the search window. 2. Describe the Announcement window 3. Explain the MLM system (Ongoing token sales): 4. Describe the promotion website Best video will receive 20,000BCMC1 ($300) and will posted on our social channels. 📍Bounty Google Form Notice: The channel must have Minimum of 1000 subscribers. Your email will be blacklisted if you submit an old video link or if you do not follow the instructions given. #BCMC1#BeforeCoinMarketCap#BCMC#Crypto#BCMCToken#Bounty