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

Пребарај: #newchapter

当前筛选 #newchapter清除筛选
DeckForge Announcement

@deckforge_official · Post #224 · 21.04.2025 г., 17:36

The story has always been there. DeckForge is more than just a game. It’s a world with its own rules, its own power, and its own history. Until now — you’ve only seen the surface. But starting this week, the veil begins to lift. We’ll reveal the origins. The forces at play. The Forge at the center of it all. Welcome to the beginning of DeckForge lore. Stay tuned — the world is about to speak.. #DeckForge#LoreUnfolds#NewChapter Join the DeckForge Community: 🌐YouTube𝕏Twitter 👉Chat👉Announcements

BadVolf

@badvolfnews · Post #1516 · 16.03.2024 г., 18:08

🇷🇺❤Today marks a monumental chapter in my journey, as I proudly announce that I've become a Russian citizen and participated in my very first election here. This significant step is more than just a formal process; it symbolizes my deep connection and commitment to my new home, its people, and its future. As I stood in the polling station, casting my vote, I was overwhelmed with a sense of responsibility and belonging. This act of civic engagement is a powerful reminder of the role we each play in shaping the course of our community and nation. It's a day filled with emotions - pride, hope, and anticipation for what lies ahead. Joining my fellow citizens in this democratic process, I felt a strong bond of unity and shared purpose. Here's to embracing new beginnings, contributing to the collective future, and making every moment count in this beautiful journey. #Citizenship#ElectionDay#NewChapter#RussianCitizen🇷🇺✨

𝑺𝒐𝒏𝒐 𝒏𝒖𝒅𝒐.

@sononoodo · Post #41458 · 01.04.2026 г., 07:39

Sono entusiasta di condividere un nuovo capitolo del mio personale brand journey! 🚀 Con grande orgoglio, annuncio il mio recente "upgrade" strategico dello stile personale: ho scelto di vestirmi, un passo fondamentale per evolvere il mio stato da "nudo" a "diversamente nudo". 👔✨ Questa scelta si allinea perfettamente con i miei valori di crescita professionale e di impatto visivo, segnando un momento chiave nella mia missione di esprimere al meglio il mio potenziale. 🌟📈#NewChapter#StyleEvolution#PersonalBranding#GrowthMindset

Notes I Never Shared 🌱

@notesinevershared · Post #69 · 28.08.2025 г., 19:20

🔄🇺🇿 #15 — 4 Kun ichida 3 ish taklifi: Hayotimdagi yangi bosqich Oradan 4 kun o‘tgach, men topshirgan Birlashgan Arab Amirliklaridagi kompaniyalardan menga qo‘ng‘iroq bo’ldi. Ular intervyu o‘tkazishdi. Tez orada 3 ta ish taklifini oldim. Qanday ish deb qiziqayotgan bo‘lsangiz, offitsiant (waiter)— bu ishga kirish va ketish uchun eng oson yo‘llardan biri. Bu jarayon menga sabr, qat’iyat va Allohga tavakkul qilishning ahamiyatini yana bir bor eslatdi. Harakat qilmasdan, faqat orzu qilish bilan hech narsaga erishib bo‘lmaydi. Har bir qadam, har bir qaror — bu yangi imkoniyatlarga yo‘l ochadi. 🔄🇬🇧 #15 — 3 Job Offers in 4 Days: A New Chapter Begins Just three days later, I received a call from the companies I had applied to in the United Arab Emirates. They conducted an interview, and soon after, I received three job offers. Curious about the role? It's a waiter position — one of the easiest entry points into the job market there. This experience reminded me of the importance of patience, determination, and placing trust in Allah. Simply dreaming without taking action leads nowhere. Every step, every decision opens doors to new opportunities. #EverythingILived#TrustInAllah#Action#Dua#Dreams#Dubai#NewChapter

Мирослава Карпович

@m1r0slavakarpovich · Post #818 · 01.03.2023 г., 06:17

С ВЕСНОЙ ВАС🤍🕊️✨ #highlevel#newchapter#goldenedition Photobombed me @hristy__🧨 Makeup & hair @elena__muah💋 #muse#яработаюмузой#actress#actrice#model#legslegslegs#elevation#higher#postcard#spring#springspringspring#springfashion#moodoftheday#photography#photooftheday#lady#mademoiselle#purelove#heavenonearth#благодарю#люблю#свеснойвас#доброеутро#petitefemme#mira#женщинамира#карповичмирослава