Layout utilities¶
Overview¶
qtypy.layout.LayoutBuilder
:- Stacking layouts with context managers.
Examples¶
#!/usr/bin/env python3
from PyQt5 import QtCore, QtWidgets
from qtypy.layout import LayoutBuilder
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
builder = LayoutBuilder(self)
with builder.vbox() as vbox:
vbox.addWidget(QtWidgets.QLabel('Title'))
with builder.hbox() as hbox:
hbox.addStretch(1)
hbox.addWidget(QtWidgets.QPushButton('OK')).clicked.connect(self.onOK)
hbox.addWidget(QtWidgets.QPushButton('Cancel')).clicked.connect(self.onCancel)
self.show()
self.raise_()
def onOK(self):
print('== OK')
def onCancel(self):
print('== Cancel')
if __name__ == '__main__':
app = QtWidgets.QApplication([])
win = MainWindow()
app.exec_()
Reference¶
Utilities for working with layouts.
-
class
qtypy.layout.
LayoutBuilder
(target)[source]¶ Layout builder. Use this to ‘stack’ layouts using context managers. For instance, instead of
l1 = QtWidgets.QHBoxLayout() l1.addWidget(...) l2 = QtWidgets.QVBoxLayout() l2.addWidget(...) l2.addLayout(l1) self.setLayout(l2)
you can do
builder = LayoutBuilder(self) with builder.vbox() as l2: l2.addWidget(...) with builder.hbox() as l1: l1.addWidget(...)
The builder class takes care of adding each layout to its parent (defined in the outer context manager), and adding the top-level layout to the target widget.
Methods that create a layout (hbox, vbox, etc) take additional positional and keyword arguments that will be passed to the parent’s addLayout() method. Intermediate container widgets (when the top-level layout must be added to a QMainWindow for instance) are created automatically.
The returned layouts are actually proxies to actual layouts, with the addWidget() method returning the added widget. This allows call chaining without using an intermediate variable, for instance
hbox.addWidget(QtWidgets.QPushButton('OK')).clicked.connect(self.okSlot)
instead of
w = QtWidgets.QPushButton('OK') hbox.addWidget(w) w.clicked.connect(self.okSlot)