@mountstorm · Post #692 · 05.08.2023 г., 16:00
Twas the night before finals, And all through the college, The students were praying For the last minute knowledge. #yeah
Hashtags
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
Пребарај: #yeah
@mountstorm · Post #692 · 05.08.2023 г., 16:00
Twas the night before finals, And all through the college, The students were praying For the last minute knowledge. #yeah
Hashtags
@mountstorm · Post #670 · 25.07.2023 г., 07:14
We need to be educated! #yeah
Hashtags
@mountstorm · Post #657 · 18.07.2023 г., 10:34
Always hate comes from below #yeah
Hashtags
@mountstorm · Post #653 · 16.07.2023 г., 04:16
That Eye Blunt Injury The incident of a blunt eye injury during a football game caused me to spend a week alone in the hospital, which led to the discovery of my sense of self. I associate mostly with being a student, as I have always been passionate about learning and developing my knowledge. However, the experience of the injury made me realize that being cautious and aware of my surroundings is also a defining part of my identity. As a student, I am constantly learning and growing, but as someone who has suffered an injury, I am also aware of my vulnerability. This experience has taught me to be more careful and attentive in my day-to-day life, especially when participating in physical activities. Overall, the experience has helped me to redefine my identity and to appreciate the importance of taking care of myself. #yeah
Hashtags
@mountstorm · Post #638 · 08.07.2023 г., 05:23
Today is the last day, last night, last late-night mafia gatherings, last dinner together, last secret friend gift, last team building, and last memorable conversations. #yeah
Hashtags
@mountstorm · Post #630 · 05.07.2023 г., 12:47
🥷 If you can climb the real mountain, why can't you climb your imagined ones? #yeah
Hashtags
@mountstorm · Post #593 · 25.05.2023 г., 10:20
Pain is temporal, remembering valuable ones is rare. #yeah
Hashtags
@mountstorm · Post #259 · 29.06.2022 г., 02:09
#yeah
Hashtags
@mountstorm · Post #203 · 06.06.2022 г., 05:35
😌 5 Exams out of 6, I got from all '5' mark #yeah
Hashtags
@mountstorm · Post #170 · 30.05.2022 г., 08:15
Summer. High School graduates still have the aftertaste of the graduation party and now are preoccupied with summer holidays. While my bro, a 9th grade graduate, can chill for the entire season, he will work on his academic interests and chill. Along with participating in extracurricular summer programs, he will be reading books, however cliche it sounds. Reading a book is like investing in real-estate. As long as you get the right book/estate, you are in a slowly-but-surely growing business. No need for a solid schedule or a measurable goal - how many pages to read daily, specific deadlines - in the beginning. Planning is important, I'd say, when and if there is already a vivid picture of what exactly you need and want to read. I started the process with whatever I had in hand - a fairy-tale collection, a magazine, or a random novel. Bit by bit, it's been getting more clear what genre/author's style is mine and what book to read next. The difference between a "good" book and a "bad" one for me is the first ten pages. Asking for advice on what to read from others is also better done in later stages, I believe. Suggested books are better added to the foundation laid by you. #yeah
Hashtags
@mountstorm · Post #187 · 04.06.2022 г., 18:20
Saturday classes 😬 = Vocab game 😋 Accuracy is fine, bro, calm down) #mountstorm#yeah
Hashtags
@mountstorm · Post #253 · 22.06.2022 г., 09:54
🥳 Finally got a certificate of Basic secondary Education with Honours 9th specialized school. P.s/ бордовый аттестат 😮💨 #oqiganlaga_mazza#yeah
Hashtags