PySide2 additional window opens only in debug mode

Viewed 27

I'm working on a basic toolkit using PySide2. I created a def and connected it to a button that opens an additional window, and it actually works fine.. but only during PyCharm debug mode. It doesn't work whether i run it from a .sh, from PyCharm or from the cmd. No errors. I verified the code is reachable using some prints before and after new_window.show().

My code:

app = QApplication(sys.argv)
win = QMainWindow()
add_win_button = QtWidgets.QPushButton(win)

def additional_window():
    new_window = QMainWindow()
    new_window.setGeometry(150, 150, 300, 300)
    new_window.setWindowTitle("Additional Window")
    new_window.show()

def window():
    win.setGeometry(200, 200, 600, 600)
    win.setWindowTitle("Main Window")
    add_win_button.setText("Add a Window")
    add_win_button.move(380, 70)
    add_win_button.clicked.connect(additional_window)
    add_win_button.adjustSize()
    win.show()
    sys.exit(app.exec_())

window()

I followed a guide to create that didn't use self to instantiate those windows. Is this the problem?

1 Answers

Ok, actually it was necessary moving the declaration outside.

app = QApplication(sys.argv)
win = QMainWindow()
add_win_button = QtWidgets.QPushButton(win)
new_window = QMainWindow()
    
def additional_window():
    new_window.setGeometry(150, 150, 300, 300)
    new_window.setWindowTitle("Additional Window")
    new_window.show()

def window():
    win.setGeometry(200, 200, 600, 600)
    win.setWindowTitle("Main Window")
    add_win_button.setText("Add a Window")
    add_win_button.move(380, 70)
    add_win_button.clicked.connect(additional_window)
    add_win_button.adjustSize()
    win.show()
    sys.exit(app.exec_())

window()
Related