PyQt5: nested layouts

RedHuli redhuli.comments at gmail.com
Fri Apr 30 01:21:18 BST 2021


Hey Rich,

Going off of what Rodrigo was saying, another issue is also in the
following lines:
inner = qtw.QVBoxLayout(self)
self.setLayout(inner)
self was already passed to the QVBoxLayout constructor, setting the layout
for TestWindow. If you do it this way setLayout() is not necessary as you
have already set the layout. You only need to do one or the other.

Another way to create your widgets and set their nested layouts could
consist of first creating the widgets:
# Widgets
id_label = qtw.QLabel('Site ID', self)
id_nbr = qtw.QLineEdit(self,
clearButtonEnabled = True,
maxLength = 16)
site_name_label = qtw.QLabel('Site Name', self)
site_name = qtw.QLineEdit(self,
clearButtonEnabled = True,
maxLength = 64)

Then creating the layout instances and not passing self as an argument:
# Layout used for widgets
row1 = qtw.QHBoxLayout()
row1.addWidget(id_label)
row1.addWidget(id_nbr)
row1.addWidget(site_name_label)
row1.addWidget(site_name)

# The main window's layout
inner = qtw.QVBoxLayout()
inner.addLayout(row1)

And finally using setLayout() for the main window or main widget:
self.setLayout(inner)

I personally find it simpler to organize my code and thinking that way. I
have attached your code. If you have any questions, let me know. Hope that
this helps!

On Fri, Apr 30, 2021 at 7:59 AM Rich Shepard <rshepard at appl-ecosys.com>
wrote:

> On Thu, 29 Apr 2021, Rodrigo de Salvo Braz wrote:
>
> > The problem occurs at line
> > row1 = qtw.QHBoxLayout(self)
>
> > When you create a layout with a QWidget argument (here, self), you are
> > saying that this will be the layout for that widget. However, you had
> > already done the same for the inner layout:
>
> > Hope that helps.
>
> Rodrigo,
>
> Yes, it helps immensly. I still have issues knowing when to use self and
> when not to use it. While I understand the concept I still get the details
> wrong.
>
> Thanks very much,
>
> Rich
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20210430/1e32cb84/attachment-0001.htm>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test.py
Type: text/x-python-script
Size: 1235 bytes
Desc: not available
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20210430/1e32cb84/attachment-0001.bin>


More information about the PyQt mailing list