P
P
pypyshka2016-07-11 16:13:56
Python
pypyshka, 2016-07-11 16:13:56

How to create a new window in PyQt5?

Good afternoon.
There is a main window created in Designer with a button. All this is saved in the test.ui file.
Also, a new empty QWidget class window was created in the Designer and saved to the test2.ui file.
The new window file test2.py contains:

def new_form():   
    new_window = uic.loadUi("interface2.ui")
    new_window.setWindowTitle("New form")
    new_window.show()

In the main window file test.py:
import test2
main_window.pushButton.clicked.connect(test2.new_form)

If you click on the button in the main window, a new window will open and immediately close. Can you please tell me how to make this window permanently displayed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey6661313, 2016-07-12
@pypyshka

reason: the new_window variable dies as soon as the new_form() function ends (why? for the glory of Satan, of course!)
Solutions:
1) create some kind of global variable. But global variables are bad form (don't know why):

new_window = None
def new_form():   
    global new_window
    new_window = uic.loadUi("interface2.ui")
    new_window.setWindowTitle("New form")
    new_window.show()

2) create a variable global array of windows (this is how I do it - it's still "bad form" but then you can delete all the created windows at once in a loop, for example...) :
мой_список_окон = []
def new_form():   
    global мой_список_окон
    new_window = uic.loadUi("interface2.ui")
    new_window.setWindowTitle("New form")
    new_window.show()
    мой_список_окон.append(new_window)

3) assign new_window to main_window's child (ideologically correct):
def new_form(parent):   
    new_window = uic.loadUi("interface2.ui")
    new_window.setWindowTitle("New form")
    new_window.show()
    new_window.setParent(parent)

import test2
main_window.pushButton.clicked.connect(lambda: test2.new_form(main_window))

4) new_window must be a variable of an object that is guaranteed not to be deleted (I don't know about the ideology... all options are correct. ):
def new_form(parent):   
    parent.new_window = uic.loadUi("interface2.ui")
    parent.new_window.setWindowTitle("New form")
    parent.new_window.show()


import test2
main_window.pushButton.clicked.connect(lambda: test2.new_form(main_window))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question