Search code examples
pythonpyqtpyqt5qwidget

Create new components on an inherited window in pyqt5


I'm working on a small GUI made in PYQT5. I have a main window with a couple of buttons which open new windows. One of these windows has an embedded matplotlib plot and 2 buttons.

So, from this existing window called "PlotWindow" I want to create a new window called "DynamicPlotWindow" but add more elements (Comboboxes, buttons, methods, etc.). In other words, I want to reuse existing windows and put more components on them. I´m able to create new DynamicPlotWindow windows, but the new components added to it aren´t visible.

Based on this question: PyQt5 Making a subclass widgets the definition of both clases is as follows:

class PlotWindow(QMainWindow): #Matplotlib embeded + 2 buttons


        def __init__(self, parent):
            super(QMainWindow, self).__init__(parent)
            self.width = 1000
            self.height = 540
            self.setGeometry(10, 10, self.width, self.height)
            ...
            self.show()

        ...

    class DynamicPlotWindow(PlotWindow):

        def __init__(self, parent):
            super(PlotWindow, self).__init__(parent)
            self.btn = QPushButton("Test") # -> Not visible
            self.btn.resize(120,30)
            self.btn.move(600,800)
            ...
            self.show()

My question is what am I doing wrong here? Is it possible to do it? Best,


Solution

  • Your code has the following errors:

    • The botton is not a child of the window so it will not be shown, the solution is to pass it to self as parent
    • The window has a size of 1000x540 but you want to place the button in the position (600,800) that is clearly outside the height: 800> 540.

    The solution is:

    self.btn = QPushButton("Test", self) 
    self.btn.resize(120,30)
    self.btn.move(600, 200) # change y coordinate