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

Резултати

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

Пребарај: #learn

当前筛选 #learn清除筛选
djangoproject

@djangoproject · Post #545 · 11.01.2018 г., 14:08

https://online.dr-chuck.com/about.php This is the web site of the "University of Dr. Chuck". I teach a number of free/online/open courses based on free and open materials and this site is the course catalog for my free courses. #learn#python

djangoproject

@djangoproject · Post #524 · 17.12.2017 г., 16:42

https://python.swaroopch.com/ A Byte of #Python "A Byte of Python" is a free book on programming using the Python language. It serves as a tutorial or guide to the Python language for a beginner audience. If all you know about computers is how to save text files, then this is the book for you. #learn

djangoproject

@djangoproject · Post #432 · 07.09.2017 г., 09:30

# In Python 3.4+ you can use # contextlib.suppress() to selectively # ignore specific exceptions: import contextlib with contextlib.suppress(FileNotFoundError): os.remove('somefile.tmp') # This is equivalent to: try: os.remove('somefile.tmp') except FileNotFoundError: pass # contextlib.suppress docstring: # # "Return a context manager that suppresses any # of the specified exceptions if they occur in the body # of a with statement and then resumes execution with # the first statement following the end of # the with statement." #python#learn

djangoproject

@djangoproject · Post #412 · 15.08.2017 г., 05:11

https://intellipaat.com/tutorial/python-tutorial/ Often, programmers fall for Python because of its minimum compilation time and speedier edit-test-debug cycle. Python is a go-programming language that has automated the way programmers code. This is indeed one of the major reasons developers have switched their interest to Python programming language. It helps you write simple scripts at relatively faster rate compared to Java, C, C++ . Get #Python Certification in just 16 Hours GET CERTIFIED #learn

djangoproject

@djangoproject · Post #284 · 31.03.2017 г., 06:53

http://docs.python-guide.org/en/latest/ Greetings, Earthling! Welcome to The Hitchhiker’s Guide to Python. This is a living, breathing guide. If you’d like to contribute, fork us on GitHub! This handcrafted guide exists to provide both novice and expert Python developers a best practice handbook to the installation, configuration, and usage of Python on a daily basis. This guide is opinionated in a way that is almost, but not quite, entirely unlike Python’s official documentation. You won’t find a list of every #Python web framework available here. Rather, you’ll find a nice concise list of highly recommended options. #learn

123•••56
ПретходнаСтраница 1 од 6Следна