How to create new PyQt4 windows from an existing window?

后端 未结 2 1739
长发绾君心
长发绾君心 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 16:02

    You can only create one QApplication. After you have created it you can create how many windows you want.

    For example:

    from PyQt4 import QtGui, QtCore
    
    class MyWindow(QtGui.QDialog):    # any super class is okay
        def __init__(self, parent=None):
            super(MyWindow, self).__init__(parent)
            self.button = QtGui.QPushButton('Press')
            layout = QtGui.QHBoxLayout()
            layout.addWidget(self.button)
            self.setLayout(layout)
            self.button.clicked.connect(self.create_child)
        def create_child(self):
            # here put the code that creates the new window and shows it.
            child = MyWindow(self)
            child.show()
    
    
    if __name__ == '__main__':
        # QApplication created only here.
        app = QtGui.QApplication([])
        window = MyWindow()
        window.show()
        app.exec_()
    

    Every time you click the button will create a new window.

    You can adapt the above example to use the windows you created with the Designer.

    On a side note:

    Never ever edit the result of pyuic. Those files should not be changed. This means: do not add the mbutton1 method to the Ui_Form.

    If you have the file mywindow_ui.py that was created by pyuic, then you create the file mywindow.py and put something like this:

    from PyQt4 import QtCore, QtGui
    from mywindow_ui import Ui_MyWindow
    
    class MyWindow(QtGui.QWidget, Ui_MyWindow):   #or whatever Q*class it is
        def __init__(self, parent=None):
            super(MyWindow, self).__init__(parent)
            self.setupUi(self)
        def create_child(self):   #here should go your mbutton1
            # stuff
    #etc.
    

    Now from your main file main.py you do:

    from PyQt4 import QtGui
    
    from mywindow import MyWindow
    
    
    # ...
    
    if __name__ == '__main__':
        app = QtGui.QApplication([])
        window = MyWindow()
        window.show()
        app.exec_()
    

提交回复
热议问题