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

Резултати

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

Пребарај: #vegetarian

当前筛选 #vegetarian清除筛选
厨渣爱美食

@eatNcook · Post #1533 · 20.11.2023 г., 21:39

#Vegetarian Vegetable Wellington flax egg 🥚 onIon 🧅 carrots 🥕 bell pepper 🫑 celery garlic 🧄 mushrooms 🍄 rosemary, sage, thyme vegan Worcestershire walnuts brown rice green lentils tomato paste garbanzo bean flour salt and pepper non-dairy milk Squirt of agave Vegan-friendly puff pastry dough

Hashtags

厨渣爱美食

@eatNcook · Post #825 · 13.10.2023 г., 21:06

#Vegetarian Roasted Eggplant dips🍆 BAINGAN BHARTA RECIPE (4-5 servings, 1h prep time): -2 eggplant Poke in holes with a fork and roast at 200C/ 400F for 45mins. 1 Tsp mustard seeds 1 Tsp cumin 1 Tsp Garam Masala 1 Tsp ground coriander 1/2 Tsp turmeric Roast in some oil 2-3mins. 1 onion, 4 cloves garlic a thumbsize piece of ginger 1 chili Chop everything. Add to the spices and fry until the onion has softened. Remove the skin from roasted eggplant and add the eggplant to the pan. 2 chopped tomatoes Salt a splash of water Add to the pan as well and stir. Let it simmer for 10mins. Finish with lemon juice and cilantro.

Hashtags

厨渣爱美食

@eatNcook · Post #585 · 15.09.2023 г., 21:17

#Vegetarian Mushroom Gyro RECIPE Mushroom "gyros": 250 g oyster mushrooms 2-3 tbsp olive oil 2 tsp dried oregano 1 tsp paprika 2 tsp smoked paprika 2 garlic cloves fresh rosemary 1 tsp brown sugar 1/2 tsp salt 1 tsp black pepper Vegan Tzatziki: 2/3 cup (160 g) vegan yogurt (I used soy) 1/2 cucumber 1-2 garlic cloves small bunch parsley + dill 2 tbsp olive oil 2 tbsp vinegar salt Other: pita (recipe is coming soon!) red onion (thinly sliced) tomato (thinly sliced + salted) fries (optional, but recommended) fresh herbs (l used parsley + mint) 1. mix mushrooms and all ingredients for the marinade. 2. For the tzatziki, grate the cucumber, salt and squeeze out water. Finely chop garlic and combine all ingredients in a bowl. 3. Fry the mushrooms in a hot pan, use a pot as weight and press while frying. Fry until slightly charred from both sides. 4. Thinly slice the onion and place them in cold water. Thinly slice the tomato and salt. 5. Assemble

Hashtags

厨渣爱美食

@eatNcook · Post #538 · 09.09.2023 г., 13:23

#Vegetarian No-Knead Focaccia Muffin Recipe (Makes 12) 350g Bread Flour 245g Water *2g Instant Yeast 7g Salt 10g Olive oil *Substitutable with 70g Levain/ Discard Toppings Smoked Sea Salt Rosemary Method FIRST PROOF Mix flour, oil, salt, instant yeast and water and let it sit for 30min. 1 set of stretch-and fold, rest 30 min. 2 sets coil fold, 30min rest in-between. Overnight cold fermentation in the refrigerator. SECOND PROOF The next day, divide the dough into 12 equal portions. Roll each portion into a ball and place in muffin tray. Proof until (almost) double. Preheat oven at 230C. Dimple, add desired toppings and bake for 18-20min. Bon Appetite.

Hashtags

厨渣爱美食

@eatNcook · Post #613 · 17.09.2023 г., 19:47

#素食 #Vegetarian Thai red curry noodle soup 🍜 1/2 a white onion 1 tsp of garlic puree 3 tsps of red curry paste 1 block of chopped tofu 4 sliced chestnut mushrooms 1 tbsp soy sauce 1 tin of coconut milk 2 portions of dry noodles 2 Pak choi cut in half lime juice, coriander and spring onion 1. Dice onion and fry in a little oil, once browning add garlic puree and red curry paste and stir and cook for 5 min. 2. Add chopped tofu and mushrooms and cook for 5 min. 3. Add 1 tbsp soy sauce, coconut milk and a splash of water and stir well. 4. Add uncooked noodles and Pak choi cut in half and place the lid to cook for 10 min. 5. Serve immediately with lime juice, coriander and spring onion.

厨渣爱美食

@eatNcook · Post #584 · 15.09.2023 г., 20:36

#Vegetarian #素食 Korean vegetable pancake For the Pancakes: • 1 Cup Flour • 1/2 tsp Kosher Salt • 1 Cup Water • 1 Cup Leek Greens, sliced thin • 1/2 Cup Carrot, grated • 3 Scallions, sliced in 1" pieces • 1/2 Cup Red Cabbage, sliced in thin 1" pieces a 1 Jalapeño, seeds removed sliced in thin 1" strips • 2 Tbsp Avocado Oil For the Sauce: • 2 Tbsp Soy Sauce • 1 Tbsp Lemon Juice • 1 tsp Water • 1 Tbsp Sesame Oil • 1 tsp Sesame Seeds Mix together the flour, salt, and water Add the veggies and mix until combined Mix together the ingredients for the sauce and set aside Preheat a large pan over medium and add the avocado oil; scoop 1/4 cup batter per pancake and flatten slightly with a spatula; cook 2-3 mins per side until golden brown and then place on a plate lined with paper towel to remove excess oil Dip in the sauce and enjoy!

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