I've made a context manager wrapper for PyQt, where __enter__
will setup the layout or widget, and __exit__
will apply it to the parent layout. Basically it reduces the lines of code needed to create a layout, and works well with indenting.
I'll use the wrapper on widgets if I want to have access to some of the methods (such as remove_border
if it's a QTreeWidget
), but I need to call the code like this:
with MyClass(QtWidgets.QTreeWidget, parent_layout) as widget:
pass
Would it be possible to have it so I can do widget = MyClass(QtWidgets.QTreeWidget, parent_layout)
, but still have it run the enter and exit methods?
Edit: Based on code_onkel's answer, I've separated the functions but kept it quite simple, so a lot of the work is automatically done.
Here's an example with QPushButton
:
class Example(object):
...
def addQPushButton(self, *args, **kwargs):
with QWidgetPushButton(self, *args, **kwargs) as widget:
return widget
@contextmanager
def QPushButton(self, *args, **kwargs):
with QWidgetPushButton(self, *args, **kwargs) as widget:
yield widget
with Example(parent) as layout:
button_1 = layout.addQPushButton('1')
with layout.QPushButton('2') as button_2:
pass