Created
December 24, 2018 00:03
-
-
Save dgovil/6c802920fbfba516e0c09b69dd30c767 to your computer and use it in GitHub Desktop.
Context Manager that adds any created widgets to a currently active widget
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
I don't recommend using this but it was just exploring an idea of automatically adding widgets | |
""" | |
import sys | |
import inspect | |
from PyQt5 import QtWidgets | |
class ActiveParent(object): | |
def __init__(self, widget): | |
super(ActiveParent, self).__init__() | |
self.widget = widget | |
self.existing_variables = [] | |
def __enter__(self): | |
"""Gets all existing variables so we only add new variables in""" | |
frame = inspect.currentframe().f_back | |
self.existing_variables = list(frame.f_locals.keys()) | |
return self | |
def __exit__( self, *args): | |
"""Now we get all the created widgets and parent them to our widget | |
All widgets must have be assigned to a variable to get picked up | |
""" | |
layout = self.widget.layout() | |
frame = inspect.currentframe().f_back | |
for name, val in frame.f_locals.items(): | |
if name in self.existing_variables: | |
continue | |
if not isinstance(val, QtWidgets.QWidget): | |
continue | |
if val.parent(): | |
continue | |
val.setParent(self.widget) | |
if layout: | |
layout.addWidget(val) | |
def main(): | |
title = "Active Parent Test" | |
size = 300 | |
win = QtWidgets.QDialog() | |
win.setWindowTitle(title) | |
win.resize(size, size) | |
with ActiveParent(win) as p: | |
btn = QtWidgets.QPushButton('test') | |
return win | |
if __name__ == '__main__': | |
app = QtWidgets.QApplication(sys.argv) | |
win = main() | |
win.show() | |
sys.exit(app.exec_()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment