How to set the central widget of existing MainWidn

2019-07-18 22:16发布

I have a code which consists of 3 classes. The classes widget1 and widget2 inherit from QFrame class and consists of several lineedit and combobox for the user to enter information.

So, what I want is: when the program is launched, it will firstly bring up the QMainWindow class with widget1 set as the central widget.

The widget1 has a Check function which is connected to a button on it. The check button will check whether a condition is true based on the data entered by the user on the page.

If the condition is true. I want the widget2 to set it as central wiget of MainWindow to replace existing central widget, the widget1.

My question is, how do I set the widget2 as the central widget of existing MainWidnow class instance?

This is the format of my code:

class widget1(QtGui.QFrame):
    def __init__(self,parent = None):
        ......
        ......

    def Check(self):
       if (condition):
           #set widget2 as central widget on MainWindow

class widget2(QtGui.QFrame):
    def __int__(self,parent = None):
        .....
        .....

class MainWindow(QtGui.QMainWindow):
    def __init__(self,parent = None):
        QtGui.QMainWindow.__init__(self,parent)
        ....
        mywidgetone = widget1()
        self.setCentralWidget(mywidgetone)

if __name__ == '__main__':
    app = QtGui.QApplicaiton(sys.argv)
    main = MainWindow()
    main.show()
    app.exec_()

2条回答
看我几分像从前
2楼-- · 2019-07-18 22:50

Another option is a panel creates all 3 widgets but set widget2 and 3 visible = false. Then when time to change, set widget1 visible=false, and widget2 visible. Etc. You set the panel as central widget, this never changes. Just the panel decides which one of its three children to show.

查看更多
狗以群分
3楼-- · 2019-07-18 23:11

I'd do the following for MainWindow:

class MainWindow(QtGui.QMainWindow):
    def __init__(self,parent = None):
        QtGui.QMainWindow.__init__(self,parent)
        ....
        self.setMyCentral(widget1)

    def setMyCentral(self, widgetClass):
        mywidget = widgetClass(self)
        self.setCentralWidget(mywidget)

and then, in widget1:

def Check(self):
   if (condition):
       self.parent().setMyCentral(widget2)

Now, please, follow the conventions: classes start in capital letters (Widget1, Widget2) and methods don't (check instead of Check)

查看更多
登录 后发表回答