How to create new PyQt4 windows from an existing window?

后端 未结 2 1744
长发绾君心
长发绾君心 2020-12-29 15:34

I\'ve been trying to call a new window from an existing one using python3 and Qt4.

I\'ve created two windows using Qt Designer (the main application and another one)

2条回答
  •  臣服心动
    2020-12-29 15:59

    Although pyuic can create executable scripts with the -x, --execute option, it is mainly intended for testing.

    The main purpose of pyuic is to create static python modules from Qt Desgner ui files that allow you to import the contained GUI classes into your application.

    Let's say you've created two ui files using Qt Designer and named them v1.ui and v2.ui.

    You would then create the two python modules like this:

    pyuic4 -o v1.py v1.ui
    pyuic4 -o v2.py v2.ui
    

    Next, you would write a separate main.py script that imports the GUI classes from the modules, and creates instances of them as needed.

    So your main.py could look something like this:

    from PyQt4 import QtGui
    from v1 import Ui_Form1
    from v2 import Ui_Form2
    
    class Form1(QtGui.QWidget, Ui_Form1):
        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            self.setupUi(self)
            self.button1.clicked.connect(self.handleButton)
            self.window2 = None
    
        def handleButton(self):
            if self.window2 is None:
                self.window2 = Form2(self)
            self.window2.show()
    
    class Form2(QtGui.QWidget, Ui_Form2):
        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            self.setupUi(self)
    
    if __name__ == '__main__':
    
        import sys
        app = QtGui.QApplication(sys.argv)
        window = Form1()
        window.show()
        sys.exit(app.exec_())
    

    Note that I have changed the names of your GUI classes slightly to avoid namespace clashes. To give the GUI classes better names, just set the objectName property of the top-level class in Qt Desgner. And don't forget to re-run pyuic after you've made your changes!

提交回复
热议问题