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

Пребарај: #punctuation

当前筛选 #punctuation清除筛选
Learn RCRussian🤍💙❤️

@learnrcrussian · Post #4384 · 21.03.2025 г., 15:00

Был бы у меня такой кот, я, может, и не женился бы никогда. If I had a cat like that, I might never have gotten married. • Может [mo-zhyt] Maybe, perhaps, probably, might 🔻This introductory word expressing possibility or probability is set off by commas in a sentence. 😉С пятницей, товарищи! #just_a_joke #just_cats #punctuation #Friday 😎 Stay with @learnRCRussian

Language Trivia 🤔

@languagetrivia · Post #490 · 16.12.2024 г., 09:47

Did you know that Spanish 🇪🇸 uses upside down exclamation and question marks (¡ and ¿) at the beginning of sentences? ¡Qué bonito! ("How beautiful!") ¿Cómo estás? ("How are you?") Creo que tienes razón, pero ¿estás completamente seguro? ("I think you're right, but are you completely sure?") Below you'll find a block of questions on these upside down punctuation marks. For each question react with 👍🏻 if you got it right and 🙈 if you got it wrong. @languagetrivia#question_block#punctuation

Language Trivia 🤔

@languagetrivia · Post #463 · 10.12.2024 г., 19:02

In the world of printing and journalism, the exclamation mark (!) has earned a variety of colorful nicknames. One of these humorous terms compares its shape to a specific part of a dog’s anatomy. Sometimes an exclamation mark is humorously referred to as “a dog’s [what]"? A) Tail 🐕 B) Nose 👃 C) Bone 🦴 D) C*ck🍆 Take the quiz below to find out @languagetrivia#punctuation#symbol#slang

Language Trivia 🤔

@languagetrivia · Post #596 · 16.01.2025 г., 10:16

✏️Did you know about the Oxford comma, also known as the serial comma? It's the final comma in a list of three or more items, placed before "and" or "or." For example: 🔵I invited my parents, Taylor Swift, and Elon Musk. Without the Oxford comma, it could look like this: 🔵I invited my parents, Taylor Swift and Elon Musk. Wait, are my parents Taylor Swift and Elon Musk?! 😅 Not everyone agrees on its usage: 🟢Proponents argue it provides clarity and prevents ambiguity 📝 🟣Opponents feel it’s unnecessary in straightforward cases and takes up space 📰 For instance, the AP Stylebook often skips it unless absolutely needed, but the Chicago Manual of Style recommends using it in all cases. Here are some examples showing how the Oxford comma can help fight ambiguity: 1️⃣Avoiding Misinterpretation: I dedicate this book to my parents, Mother Teresa, and the pope. Without the Oxford comma: I dedicate this book to my parents, Mother Teresa and the pope. This could imply that your parents are Mother Teresa and the pope. 😳 2️⃣Clarifying Groupings: We had coffee, cheese and crackers, and grapes. Without the Oxford comma: We had coffee, cheese and crackers and grapes. This could suggest that "crackers and grapes" are a combined dish. 🍇🧀 3️⃣Costly Consequences: O'Connor v. Oakhurst Dairy (2017) was a U.S. legal case where truck drivers sued for overtime pay, challenging an ambiguous Maine law that lacked an Oxford comma. The law exempted work involving "packing for shipment or distribution" of goods. Without a comma, it was unclear if "distribution" was part of "packing" or a separate activity. The court sided with the drivers, interpreting the ambiguity in their favor, leading to a $5 million payout. 💸 📌Ultimately, whether or not you use the Oxford comma is up to you, but the key is to be consistent. And it's also a good idea to use it in cases where it can help prevent ambiguity and misinterpretation! Sources: Grammarly |Wikipedia Tap ❤️ if you found this interesting @languagetrivia#grammar#punctuation#fact