Search code examples
pythonpyqtpyqt4

Custom widget does not appear on Main Window


I've trying to create a custom widget and make it appear on Grid Layout on the main window.

class MyCustomWidget(QtGui.QWidget):
    def __init__(self):
        super(MyCustomWidget, self).__init__()
        self.setupUi()

    def setupUi(self):
        self.testText = QtGui.QLabel()
        font = QtGui.QFont()
        font.setPointSize(8)
        font.setBold(True)
        font.setWeight(75)
        self.testText.setFont(font)
        self.testText.setAlignment(QtCore.Qt.AlignCenter)
        self.testText.setObjectName(_fromUtf8("patientText"))
        self.testText.setText("Test")

class UIMainWindow(object):
    def setupUi(self, MainWindow):
        ...
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        ...

        self.test = MyCustomWidget()
        self.gridLayout.addWidget(self.test)

When I run this code, main window appears but there is nothing about the widget that I created. If I simply add an QLabel to grid layout, it appears.


Solution

  • As is, your MyCustomWidget is simply a standard widget with an attribute testText containing a QLabel. If you want it to contain subwidgets that will show on your main window, you need to instantiate a layout, add the sub widgets to the layout, then add the layout to MyCustomWidget:

    At the end of MyCustomWidget's setupUi

    self.gridLayout = QtGui.QGridLayout()
    self.gridLayout.setObjectName(_fromUtf8("MyCustomWidgetLayout"))
    
    self.gridLayout.addWidget(self.testText)
    
    #add all other widgets here
    
    self.setLayout(self.gridLayout)
    

    You can also create embedded layouts, by calling addLayout method on the parent layout and passing it the child layout !