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

Резултати

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

Пребарај: #binusedtissues

当前筛选 #binusedtissues清除筛选
NEA Singapore

@NEASingapore · Post #310 · 28.01.2022 г., 03:45

Our Wordle of the day – did you manage to get yours right today? Don’t forget to clear your table after eating at our hawker centres, coffeeshops and food courts. P.S. You don’t have to clean your table, as cleaners will be cleaning and sanitising tables. #ClearYourTable#ReturnYourTray#BinUsedTissues

NEA Singapore

@NEASingapore · Post #216 · 22.06.2021 г., 03:13

As we begin dining out again, remember to practise good hygiene, to protect ourselves, other diners, and our cleaners – many of whom are seniors. When you’re done eating, remember to #ClearYourTable, #ReturnYourTray and #BinUsedTissues. Leaving litter on tables at our public dining places is an offence. NEA is taking an advisory approach in the lead-up to 1 Sep 2021, after which enforcement action will be taken against patrons who fail to heed our officers’ advice. www.nea.gov.sg/media/news/advisories/index/clear-table-as-dine-in-resumes

NEA Singapore

@NEASingapore · Post #215 · 21.06.2021 г., 03:30

As dine-in gradually resumes from today, let’s do our part in keeping our favourite public dining spaces and our cleaners safe by remembering to #ReturnYourTray, #ClearYourTable and #BinUsedTissues. If we simply get up and walk away, the dirty crockery and food remnants can attract unwanted pests. Our used tissues also carry germs that pose potential health risks to cleaners and other diners.

NEA Singapore

@NEASingapore · Post #705 · 23.11.2023 г., 01:02

Expectation: All ready to order my beloved hawker delights 😍 Reality: Oh no, the previous diners did not clear their tables 🥴 Let's play our part in keeping #OurHawkerCentres clean, by clearing our used tray and crockery. Details and FAQs here: www.nea.gov.sg/clean-tables #ClearYourTable#ReturnYourTray#BinUsedTissues

NEA Singapore

@NEASingapore · Post #221 · 25.06.2021 г., 10:22

Here’s what the same area at Queen’s St Hawker Centre looks like in 2016 and 2021. What a dramatic transformation we've seen lately! Better tray return infrastructure and a new cleaning workflow are initiatives we’ve adopted to ensure cleaner and safer public dining places. Diners and cleaners at #OurHawkerCentres have played a great part in making this system work. So next time you’re dining at #OurHawkerCentres, be part of that change and #ClearYourTable, #ReturnYourTray and #BinUsedTissues to keep our public dining places clean and safe for everyone. Thank You - to our cleaners, fellow diners and all of you, for supporting us! ❤️

NEA Singapore

@NEASingapore · Post #187 · 12.05.2021 г., 02:30

#DidYouKnow that our cleaners do more than just clear our tables? They also need to sanitise tables, clear the tray/crockery return stations, and return clean crockery to the stalls. Let’s do our part to help our cleaners! #ReturnYourTray#ClearYourTable#BinUsedTissues

NEA Singapore

@NEASingapore · Post #740 · 11.01.2024 г., 01:02

Savour the perfect blend of sweet, spicy, and tangy tastes of Rojak - Singapore's iconic hawker dish! 🥗🍍🥒 Whether you love it with a generous serving of thick savoury sauce or prefer it with a spicy kick, Rojak is certainly a good treat for our taste buds. P.S. Don’t forget to return your used tray and crockery after enjoying your meal! #OurHawkerCentres#OurHawkerCulture#ClearYourTable#ReturnYourTray#BinUsedTissues

NEA Singapore

@NEASingapore · Post #734 · 02.01.2024 г., 03:47

Extending our heartfelt appreciation to diners who have been returning their used trays and crockery. This small act goes a long way towards ensuring a pleasant dining experience for everyone. Let's continue to keep #OurHawkerCentres clean this new year! Details and #FAQs here: www.nea.gov.sg/clean-tables #ClearYourTable#ReturnYourTray#BinUsedTissues

12
ПретходнаСтраница 1 од 2Следна