Search code examples
pythonpython-3.xpyside2

how to open new window using QUiLoader() with pyside2


I have a main window desiged with qtdesigner. when I press a button, I would like to open a new window. To do that, I was thinking it was possible to use the Qt loader function and I wrote this function (this function is executed when I press a button in my main window).

def open_new_window(self):
    ui_file = QFile('gui/new_window.ui')
    ui_file.open(QFile.ReadOnly)
    loader = QUiLoader()
    self.window = loader.load(ui_file)
    ui_file.close()

    return

but when I do that, It close the program. Any Idea on what's wrong ? Can I use the loader function to open my uifile ? It is working for personalized widget import, why not for a new window ?

edit:

I changed the function a litle bit:

def open_new_window(self):

    ui_file = QFile('gui/new_window.ui')
    ui_file.open(QFile.ReadOnly)  
    loader = QUiLoader()
    window = loader.load(ui_file)
    window.show()
    ui_file.close()

    return

This time the 2nd window is opening, but closing instantaneously...


Solution

  • Ok, I got it. The right code is:

    def open_new_window(self):
    
        ui_file = QFile('gui/new_window.ui')
        ui_file.open(QFile.ReadOnly)  
        loader = QUiLoader()
        self.window2 = loader.load(ui_file)
        self.window2.show()
        ui_file.close()
    
        return
    

    What I changed: - I insert the "self." in front of the window call. Without that, the window close immediately because the function is ended. With the self it remains alive. - I also changed the name of the window in "window2". The reason is that when I call my main window, I already used "window". As a result it replace the previous one. with a new name, both stay open!

    regards