2

Let's say I have a MainWindow.ui that defines the layout of MainWindow.py, where MainWindow.py looks a little like this:

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = uic.loadUi('MainWindow.ui')

MainWindow.ui holds two (actually three) widgets. A simple QLabel text_lbl for argument's sake, and an empty QWidget sub_widget. These two widgets are held in central_widget.

We also have a SubWidget.ui. SubWidget.ui can be anything, really, but let's say it holds a lot of labels and spinboxes. SubWidget.py looks a lot like MainWindow.py, except it holds a lot of signals and slots:

class SubWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = uic.loadUi('SubWidget.ui')

        # A lot of interesting stuff here.

What I want to do, is put an instance of SubWidget in MainWindow's sub_widget. The obvious thing for me to do would be to add the following lines of code to MainWindow.py's __init__:

from SubWidget import SubWidget  # Though really this shouldn't be in
                                     # __init__, but you get the idea.
self.ui.sub_widget = SubWidget()

Which simply doesn't do anything. I eventually achieved rendering SubWidget over the main window's contents and complaining about MainWindow already having a layout, but I lost that code in the midst of all fiddling.

How do I achieve this?

edit: I forgot to mention. self.ui.central_layout.addWidget(SubWidget()) visually achieves what I'm trying to do, but if I ever decide to add UI elements beneath that in the .ui file, that simply won't work.

Ruben Bakker
  • 446
  • 1
  • 5
  • 11

1 Answers1

0

If you can't, or for whatever reason just don't want to, use widget promotion, then the most obvious solution is to make the SubWidget a child of the place-holder widget.

Since the place-holder widget doesn't yet have a child, you can't give it layout in Qt Designer, so you will have to do it all programmatically:

    layout = QtGui.QVBoxLayout(self.ui.empty_widget)
    layout.setContentsMargins(0, 0, 0, 0)
    self.ui.sub_widget = SubWidget()
    layout.addWidget(self.ui.sub_widget)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336