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

Пребарај: #joinusnow

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

@slex_io · Post #105 · 01.10.2023 г., 08:09

📢Open Doors for Listing on SLEX Exchange!🚀 🎉Starting October 5th, we're officially launching our listing campaign on the SLEX platform! If you've been seeking a robust platform for your project, now is the moment. 🤝Why list with SLEX? ✅Liquidity Support & Global Promotion - We've got your back with robust liquidity options and a global promotional strategy. ✅Integration with Slavi Wallet & Fiat Pairing - Seamless integration and more trading pairs to enhance user experience. ✅ Personalized Guidance & Rapid Listing - A dedicated team to guide you through every step for a smooth listing process. ✅CMC and Coingecko Assistance - We facilitate smoother interactions with major platforms for your token's recognition. ✅Vibrant User Base & Market-Making Services - Access to our engaged community and top-tier market-making solutions. 📝Follow this link and submit an application to take a chance to be listed on the SLEX platform:🔗surl.li/lbxas #SLEXListings#CryptoEvolution#JoinUsNow Email | Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter

Airdrop Market Pro

@airdrop_market_pro · Post #726 · 29.07.2024 г., 10:33

Subscribe to our channel and receive a reward in Shiba Inu cryptocurrency! 🐕💰 Don't miss out on this exclusive offer! 🚀#CryptoRewards#ShibaInu#JoinUsNow 165 / 5 000 Подпишитесь на наш канал и получите вознаграждение в криптовалюте Сиба-ину! 🐕💰 Не упустите эксклюзивное предложение! 🚀#CryptoRewards#ShibaInu#JoinNusNow

NFT & Airdrop News

@airdrop_nft1 · Post #722 · 29.07.2024 г., 10:34

Subscribe to our channel and receive a reward in Shiba Inu cryptocurrency! 🐕💰 Don't miss out on this exclusive offer! 🚀#CryptoRewards#ShibaInu#JoinUsNow 165 / 5 000 Подпишитесь на наш канал и получите вознаграждение в криптовалюте Сиба-ину! 🐕💰 Не упустите эксклюзивное предложение! 🚀#CryptoRewards#ShibaInu#JoinNusNow

Airdrop Strikers™

@airdropstrikers · Post #1187 · 16.04.2023 г., 15:33

By participating in our airdrop campaign, you will not only get a chance to earn JIM tokens, but you will also get an opportunity to be a part of the most revolutionary project of the year. So, don't miss out on this amazing opportunity and join us now! 🙌 https://gleam.io/CmtmH/jimmy-project-airdrop-campaign Spread the word and invite your friends to join the Jimmy project community. Together, we will soar to new heights!🚀#JimmyProject#Airdrop#Cryptocurrency#Blockchain#EarnTokens#JoinUsNow Total $25.000 worth JIM Token supply will be distributed to participants according to points collected. Complete all tasks to benefit airdrop in full! 10 Referral Champions will share 1000 USDT Prize pool!

Andijan Development Center

@adceducate · Post #7940 · 15.09.2023 г., 10:55

📢 Exciting News! 📢 Join our IELTS course with Teacher Danila Polikarpov! 📚✨ 🗓 When: Every Tuesday, Thursday, and Saturday 🕘 Time: 9:00 AM 📍 Where: Mashrab 19A (Hotel branch) 🌟 Why choose our IELTS course? ✅ Expert guidance from Teacher Danila ✅ Proven strategies for success ✅ Comprehensive test preparation ✅ Improve your English skills Don't miss this opportunity to boost your IELTS scores and achieve your goals! 🚀 Enroll today and take the first step towards your IELTS success. Limited seats available, so act fast! Contact us for more information or to reserve your spot. Our branches📍 📍Main office (A. Khaydarov 10) 📍Tennis court (Mashrab 19A) 📍Dialogue (Bobur Shokh 11) 📍Eski shahar (Cholpon Shokh 181) 📍Orange (Lomonosov 43) 📍School (Mangulik 14) If you have any questions, do not hesitate to contact us☎️ +998742261078 | +998742281121 | +998958505111 | +998742276163 | +998742252536 | +998952017878 or write on Telegram @admofadc 🔗 Follow ADC Andijan on social media: Telegram | Instagram | Facebook | Tik-Tok #IELTS#EnglishCourse#LearnEnglish#IELTSPreparation#SuccessInIELTS#TeacherDanila#JoinUsNow