Skip to content Skip to sidebar Skip to footer

How To Put Widgets Inside A Pyqt Qmdisubwindow

Sorry, my question may sound very stupid but Frankly i spend a lot of time on internet trying to figure out how to add a widgets to QMdiSubWindow, I mean a Multiple Widgets not jus

Solution 1:

The hierarchy of widgets and layouts should always follow

widget -> layout -> widget -> layout -> widget -> ...

where each widget can only have one layout, but each layout can contain multiple widgets (note that for simplicity the above only shows one widget per layout).

So, what you need to do is create a widget which contains a layout, and that layout contains the QPushButton andQLineEdit`. For example:

# construct the top level widget
widget = QWidget()
# construct the top level layout
layout = QVBoxLayout(widget)

# create the widgets to add to the layout
button = QPushButton('My Button')
lineedit = QLineEdit()

# add the widgets to the layout
layout.addWidget(button)
layout.addWidget(lineedit)

# set the layout on the widget
widget.setLayout(layout)
# we now have a single widget that contains a layout and 2 widgets

This allows you to effectively encapsulate multiple widgets inside a single widget (and is how a lot of the more complex Qt widgets are created internally, for instance the QSpinBox). So if you want another complex widget inside the layout above, you could again make another widget2 = QWidget(), create a layout (for instance layout2 = QHBoxLayout(widget2)), and then add multiple widgets to it. Once done, add the widget2 widget to the original layout (layout.addWidget(widget2)).

Hopefully you can now see how to construct a single complex widget from an arbitrary number of child widgets and layouts.

At this point you can now set the single widget to an existing QMdiSubWIndow

# now add this widget to the QMdiSubWindow
mdisubwindow.setWidget(widget)

or alternatively, call the convenience function on the QMdiArea to create a new QMdiSubWindow with the widget:

mdisubwindow = mdiarea.addSubWindow(widget)

Note: For your specific example, you don't actually need to construct widget2 to encapsulate the QHBoxLayout. You can add a QHBoxLayout (layout2 in my rough example above) directly to the original layout by calling layout.addLayout(layout2). However, this is more of a special case, and the general principle of encapsulation above of alternating widgets and layouts is more generalisable once you start making your own widget classes in order to re-use code.

Post a Comment for "How To Put Widgets Inside A Pyqt Qmdisubwindow"