简体   繁体   中英

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.

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM