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

Резултати

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

Пребарај: #ios12

当前筛选 #ios12清除筛选
🦅 [ perspective ix ]

@perspectiveix · Post #1337 · 18.06.2018 г., 12:00

📰#iXDailyBrief STAT ⚡️ 54% of people say playlists are replacing albums in their listening habits. (Source: DiMA) INSIGHT 💸 Attention Economy: Dealing with Information Overload: prs.pctvix.co/2t78WJh OTHER NEWS ⏳ First look at #Instagram’s self-policing Time Well Spent tool: t.me/iXNews/27652 🚫#Facebook bans weapons accessories from being advertised to minors: t.me/iXNews/27669 ⚽️ Paul Pogba owns the most influential Instagram account among Premier League players: prs.pctvix.co/2MxuUNA 🗺#iOS12 will automatically share your iPhone location during 911 calls: t.me/iXNews/27678 💰#Google makes $550M strategic investment in Chinese e-commerce firm JD: t.me/iXNews/27672 🇮🇳 Almost 1 million people 'testing' #WhatsApp payments service in India: prs.pctvix.co/2t6eaF8 EXTRA ⬇️ 2018 Annual Music Report by the Digital Music Alliance (PDF): prs.pctvix.co/2MCdqzZ — “The future depends on what you do today.” – Mahatma Gandhi Have a great week! Ben, @iXNews

🦅 [ perspective ix ]

@perspectiveix · Post #1317 · 07.06.2018 г., 12:00

​​📰#iXDailyBrief STAT ⚡️ Video consumption on mobile has been on the rise since 2012, but really started to shoot upwards in 2015, with the global number of minutes viewed per day rising from around 14 minutes in 2015 to an estimated 35 minutes in 2018. (Source: Econsultancy) INSIGHT 🏚 Photos on social media can predict the health of neighbourhoods: t.me/iXNews/26929 OTHER NEWS 📈#Revolut announces a Robinhood-like trading product: t.me/iXNews/26927 🛍#Facebook launches ads in Marketplace: prs.pctvix.co/2M4AAyF 🎧 Limited #Siri support for music apps like #Spotify is possible in #iOS12: t.me/iXNews/26925 💰#Coinbase is acquiring a securities dealer in order to trade your startup tokens: t.me/iXNews/26923 EXTRA 👨🏻‍🎨 When Crypto Meets Conceptual Art, Things Get Weird: prs.pctvix.co/2M5pEAJ — How do you like #iXDailyBrief? 👍 I like it! 😑 I don't really read it! 👎 I don't like it! Feedback: @iXContactBot Thank you! Ben, @iXNews

🦅 [ perspective ix ]

@perspectiveix · Post #1359 · 26.06.2018 г., 12:00

📰#iXDailyBrief STAT ⚡️ The leading activity in apps is digital audio, with the average US adult listening to over 50 minutes of audio via mobile apps per day. Social networking is next, with 40 minutes of app time. The other major categories are mobile video, gaming and messaging. Of these five, gaming is growing most slowly. (Source: eMarketer) INSIGHT 📺 How brands are using #Instagram’s new long-form video feature, #IGTV: prs.pctvix.co/2yPgJAC OTHER NEWS 🇻🇪 Venezuela is blocking access to the Tor network: t.me/iXNews/28209 📱#iOS12 is all about making your phone work better (Public Beta Available Now): t.me/iXNews/28205 💰#VidCon’s new grant will award one emerging YouTuber $2,000 each week for a year: t.me/iXNews/28186 🐦#Twitter returns to #AppleWatch thanks to #Chirp: t.me/iXNews/28182 🇨🇳 John Oliver is erased from Chinese internet following segment on China: t.me/iXNews/28183 — ☕️ If you like our channel, please support us: prs.pctvix.co/2taiWBz — "Success is no accident. It is hard work, perseverance, learning, studying, sacrifice and most of all, love of what you are doing or learning to do." ― Pele Ben, @iXNews