Skip to content

Instantly share code, notes, and snippets.

@akey7
Last active September 7, 2020 22:29
Show Gist options
  • Save akey7/87d59752d9c7e2349a934439a95a4b46 to your computer and use it in GitHub Desktop.
Save akey7/87d59752d9c7e2349a934439a95a4b46 to your computer and use it in GitHub Desktop.
Qt Recursive Structure Form
import sys
from typing import Any
from PySide2.QtWidgets import ( # type: ignore
QVBoxLayout,
QLineEdit,
QPushButton,
QLabel,
QFormLayout,
QTabWidget,
QWidget,
QMainWindow,
QApplication,
QScrollArea,
QGroupBox,
QComboBox,
)
class RecursiveStructureForm(QWidget):
def __init__(self, parent=None):
super(RecursiveStructureForm, self).__init__(parent)
widget = QWidget()
self.form_layout = QFormLayout()
widget.setLayout(self.form_layout)
scroll = QScrollArea()
scroll.setWidget(widget)
scroll.setWidgetResizable(True)
scroll.setFixedHeight(400)
scroll.setFixedWidth(400)
layout = QVBoxLayout(self)
layout.addWidget(scroll)
def setup(self):
for i in range(20):
group_box = QGroupBox(str(i))
group_box_layout = QFormLayout()
group_box_layout.addRow(QLabel("foo"), QLabel("bar"))
group_box.setLayout(group_box_layout)
self.form_layout.addRow(group_box)
def rst(self, root: Any, key: str = "root", parent_layout: QFormLayout = None) -> None:
layout = self.form_layout if parent_layout is None else parent_layout
if type(root) is dict and len(root.keys()) > 0:
for k, v in root.items():
child_widget = QGroupBox(k)
child_layout = QFormLayout()
child_widget.setLayout(child_layout)
layout.addRow(child_widget)
self.rst(v, f"{key}['{k}']", child_layout)
elif type(root) is dict and len(root.keys()) == 0:
print(">>> Skipping key with empty dictionary as value", key)
elif type(root) is list and len(root) > 0 and type(root[0]) is dict:
for i, x in enumerate(root):
child_widget = QGroupBox(str(i))
child_layout = QFormLayout()
child_widget.setLayout(child_layout)
layout.addRow(child_widget)
self.rst(x, f"{key}[{i}]", child_layout)
else:
layout.addRow(QLabel(str(key)), QLabel(str(root)))
if __name__ == "__main__":
hard = {
"alpha": {
"zulu": "yankee",
"victor": "uniform",
"bravo": [
1,
"awesome",
"list",
],
"delta": [
{
"deeper": "recursion",
"what would be": "the iterative solution?",
}
],
"echo": [],
"golf": {},
}
}
# Create the Qt Application
app = QApplication(sys.argv)
# Create and show the form
rsf = RecursiveStructureForm()
rsf.rst(hard)
rsf.show()
# Run the main Qt loop
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment