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

Резултати

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

Пребарај: #asyncio

当前筛选 #asyncio清除筛选
djangoproject

@djangoproject · Post #96 · 11.07.2016 г., 12:16

https://docs.python.org/3/library/asyncio-task.html#asyncio.run_coroutine_threadsafe #asyncio.run_coroutine_threadsafe(coro, loop) Submit a coroutine object to a given event loop. Return a concurrent.futures.Future to access the result.

Hashtags

djangoproject

@djangoproject · Post #75 · 28.06.2016 г., 10:29

https://docs.python.org/3/library/asyncio-eventloop.html The event loop is the central execution device provided by #asyncio. It provides multiple facilities, including: Registering, executing and cancelling delayed calls (timeouts). Creating client and server transports for various kinds of communication. Launching subprocesses and the associated transports for communication with an external program. Delegating costly function calls to a pool of threads.

Hashtags

djangoproject

@djangoproject · Post #337 · 09.05.2017 г., 08:28

http://blog.povilasb.com/posts/python-asyncio-vs-nginx-performance/ While I was playing with Python #asyncio I got interested in how well it performs serving data over TLS compared to #Nginx. So I implemented a small HTTPS server with asyncio:

djangoproject

@djangoproject · Post #152 · 03.09.2016 г., 20:18

https://glyph.twistedmatrix.com/2014/02/unyielding.html As we know, #threads are a bad idea, (for most purposes). Threads make local reasoning difficult, and local reasoning is perhaps the most important thing in software development. With the word “threads”, I am referring to shared-state multithreading, despite the fact that there are languages, like Erlang and Haskell which refer to concurrent processes – those which do not implicitly share state, and require explicit coordination – as “threads”. #asyncio

djangoproject

@djangoproject · Post #311 · 25.04.2017 г., 11:59

http://programtalk.com/python-examples/aiohttp.web.Application/?ipage=1 Here are the examples of the python api #aiohttp.web.Application taken from open source projects. By voting up you can indicate which examples are most useful and appropriate. #asyncio#learn

djangoproject

@djangoproject · Post #268 · 26.02.2017 г., 05:52

https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html 👌Making 1 million requests with python -#aiohttp Apr 22, 2016 - by Paweł Miech - about: #asyncio, aiohttp, #python In this post I’d like to test limits of python aiohttp and check its performance in terms of requests per minute. Everyone knows that asynchronous code performs better when applied to network operations, but it’s still interesting to check this assumption and understand how exactly it is better and why it’s is better. I’m going to check it by trying to make 1 million #requests with aiohttp client. How many requests per minute will aiohttp make? What kind of exceptions and crashes can you expect when you try to make such volume of requests with very primitive scripts? What are main gotchas that you need to think about when trying to make such volume of requests?

djangoproject

@djangoproject · Post #319 · 29.04.2017 г., 07:54

https://github.com/aio-libs/aiobotocore Async client for amazon services using #botocore and #aiohttp/#asyncio. Main purpose of this library to support amazon s3 api, but other services should work (may be with minor fixes). For now we have tested only upload/download api for s3, other users report that SQS and Dynamo services work also. More tests coming soon.

djangoproject

@djangoproject · Post #98 · 11.07.2016 г., 12:22

https://docs.python.org/3/library/asyncio.html #asyncio #Asynchronous programming is more complex than classical “#sequential” programming: see the Develop with asyncio page which lists common traps and explains how to avoid them. Enable the debug mode during development to detect common issues.

djangoproject

@djangoproject · Post #287 · 04.04.2017 г., 21:04

http://stackoverflow.com/questions/32054066/python-how-to-run-multiple-coroutines-concurrently-using-asyncio how to run multiple #coroutines#concurrently using #asyncio? You can use #asyncio.async() to run as many #coroutines as you want, before executing blocking call for starting event loop.

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