Search code examples
pythonpyqtqt-designer

How to call a QWidget from another QWidget in PyQt


I am developping an application with PyQt based on a QWidget. I put my whole app inside a class (named "Example"). Inside this app, I have a button which calls to another QWidget window (named "Report Widget") I designed on QtDesigner and opens it. The problem is that I don't know how to do this. Here is the method I use (which comes from something I found on internet). On my main class "Example", a method defines the Button calling for the "Report Widget" :

ReportBtn = QtGui.QPushButton("Generate report")
ReportBtn.clicked.connect(self.ShowReportWidget)

The second line calls the ShowReportWidget method of the Example (main) class :

def ShowReportWidget(self):
    self.f = QtGui.QWidget()
    self.ReportWidget = ReportWidget(self.f)
    self.ReportWidget.show()

This method calls the class ReportWidget, which is a class from the Example (main) class :

class ReportWidget(QtGui.QWidget):
def __init__(self, parent = None):
    QtGui.QWidget.__init__(self)
    self.ui = rw.Ui_ReportWidget()
    self.ui.setupUi(parent)

and finally, this class refers to an outer class (Ui_ReportWidget), contained in another separate Python file (the one generated from the QtDesigner .ui file), which I import as rw in the beginning of my script.

The problem is that with this method, when I click on the Report Widget button, a new window pops but is empty. The content of the Ui_ReportWidget class is not loaded.

I hope my question is clear enough.

Thanks


Solution

  • SetupUi takes an Qwidget as input , while the init() function should take the calling QObject as the parent.

    def ShowReportWidget(self):
        self.f = QtGui.QWidget()
        self.ReportWidget = ReportWidget(self)
        self.ReportWidget.setupUi(self.f)
        self.f.exec_()
    
    class ReportWidget(QtGui.QWidget):
        def __init__(self, parent = None):
            QtGui.QWidget.__init__(self,parent)
    
        def setupUi(self,Widget):
            self.ui = rw.Ui_ReportWidget()
            self.ui.setupUi(Widget)