Cannot create a new window in PyQt without it havi

2019-02-27 17:11发布

问题:

I started coding a simple text editor in Python with PyQt and I ran into this problem: for the "New document" button I want to open a new empty text editor which stays open no matter what happened to the first window. The problem is that the only way I got it to show the window is if I send self as a parameter(making it the parent) which leads to the second window closing when the parent closes.

Here's my constructor:

class Main(QtGui.QMainWindow):

def __init__(self, ctrl, parent=None):
    QtGui.QMainWindow.__init__(self, parent)

and here's the method that opens a new window:

def new(self):
    repo = Repository()
    ctrl = Controller(repo)
    new_win = Main(ctrl)
    new_win.show()

Note: when the code that is here doesn't work, it just doesn't show the second window

Edit: decided I should post all my code, so here it goes:

import sys

from PyQt4 import QtGui

from src.controller import Controller
from src.repository import Repository


class Main(QtGui.QMainWindow):

    nr_of_instances = -1

    def __init__(self, ctrl, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        Main.nr_of_instances += 1
        #ui elements
        self._toolbar = None
        self._menuBar = None
        self._file = None
        self._edit = None
        self._view = None
        self._formatBar = None
        self._statusBar = None
        self._text = None

        #actions
        self._newAction = None
        self._openAction = None
        self._saveAction = None
        self._saveAsAction = None

        #
        self._controller = ctrl

        self.init_ui()

    def init_ui(self):
        self._text = QtGui.QTextEdit(self)
        self.setCentralWidget(self._text)

        self.init_toolbar()
        self.init_formatBar()
        self.init_menuBar()
        self._statusBar = self.statusBar()

        self.setGeometry(50+(50*Main.nr_of_instances), 100+(50*Main.nr_of_instances), 800, 400)

        self.setWindowTitle("KekWriter")

    @staticmethod
    def new(self):
        repo = Repository()
        ctrl = Controller(repo)
        spawn = Main(ctrl)
        spawn.show()

    def set_title(self):
        if self._controller.get_file_name() != 0:
            new_title = self.windowTitle().split(" - ")
            new_title[0].strip()
            self.setWindowTitle(new_title[0]+" - "+self._controller.get_file_name())

    def open(self):
        fn = QtGui.QFileDialog.getOpenFileName(self, 'Open File', ".")
        self._controller.set_file_name(fn)
        try:
            if fn != '':
                self._text.setText(self._controller.open())
            self.set_title()
        except UnicodeDecodeError as msg:
            QtGui.QMessageBox.information(self, "Eroare!", "Tip de fisier invalid!")

    def _save_as(self):
        fn = QtGui.QFileDialog.getSaveFileName(self, 'Save File As', ".")
        print(fn)
        if fn != '':
            self._controller.set_file_name(fn)
            self._controller.save(self._text.toPlainText())
            self.set_title()

    def save(self):
        fn = self._controller.get_file_name()
        if fn == '':
            self._save_as()
        else:
            self._controller.save(self._text.toPlainText())
            self.set_title()

    def init_toolbar(self):
        self._newAction = QtGui.QAction(QtGui.QIcon("icons/new.png"), "New", self)
        self._newAction.setStatusTip("Creates a new document")
        self._newAction.setShortcut("Ctrl+N")
        self._newAction.triggered.connect(self.new)

        self._openAction = QtGui.QAction(QtGui.QIcon("icons/open.png"), "Open", self)
        self._openAction.setStatusTip("Opens existing document")
        self._openAction.setShortcut("Ctrl+O")
        self._openAction.triggered.connect(self.open)

        self._saveAction = QtGui.QAction(QtGui.QIcon("icons/save.png"), "Save", self)
        self._saveAction.setStatusTip("Saves current document")
        self._saveAction.setShortcut("Ctrl+S")
        self._saveAction.triggered.connect(self.save)

        self._saveAsAction = QtGui.QAction(QtGui.QIcon("icons/save_as.png"), "Save as", self)
        self._saveAsAction.setStatusTip("Saves current document with another name")
        self._saveAsAction.setShortcut("Ctrl+Shift+S")
        self._saveAsAction.triggered.connect(self._save_as)

        self._toolbar = self.addToolBar("Options")

        self._toolbar.addAction(self._newAction)
        self._toolbar.addAction(self._openAction)
        self._toolbar.addAction(self._saveAction)
        self._toolbar.addAction(self._saveAsAction)

        self.addToolBarBreak()

    def init_menuBar(self):
        self._menuBar = self.menuBar()
        self._file = self._menuBar.addMenu("File")
        self._edit = self._menuBar.addMenu("Edit")
        self._view = self._menuBar.addMenu("View")

        #file
        self._file.addAction(self._newAction)
        self._file.addAction(self._openAction)
        self._file.addAction(self._saveAction)
        self._file.addAction(self._saveAsAction)

    def init_formatBar(self):
        self._formatBar = self.addToolBar("Format")
        self.addToolBarBreak()


def main():
    app = QtGui.QApplication(sys.argv)
    repo = Repository()
    ctrl = Controller(repo)
    main = Main(ctrl)
    main.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

回答1:

The reason your second window doesn't show is because the window object goes out of scope and is garbage collected. You need to store a reference to the second window somewhere which won't be deleted until the window is closed.

There are a few ways to do this that I can think of, but it is really up to you with how you want to structure your program.

  1. Have a class attribute of Main which is a list. This list will thus be common to all instances and you can append a new instance to that list when it is created. As long as one instance exists, the window shouldn't be garbage collected (I think)

  2. Don't instantiate a QMainWindow initially, but instead instantiate a class that will hold references to windows. When a new window is created, sore the reference to the new window in this object.

Hopefully this gives you an idea of what is wrong so you can solve it in a way that suits the layout of your program


Update

For a rough guide of how you would do option 2:

class WindowContainer(object):
    def __init__(self):
        self.window_list = []
        self.add_new_window()

    def add_new_window(self):
        repo = Repository()
        ctrl = Controller(repo)
        spawn = Main(ctrl, self)
        self.window_list.append(spawn)
        spawn.show()


class Main(QtGui.QMainWindow):
    def __init__(self, ctrl, window_container, parent=None):
        QtGui.QMainWindow.__init__(self, parent) 
        ...
        self.window_container = window_container
        ...

    ...

    def init_toolbar(self):
        ...
        self._newAction.triggered.connect(self.window_container.add_new_window)
        ...

    ...


def main():
    app = QtGui.QApplication(sys.argv)
    # this variable will never go out of scope
    window_container = WindowContainer()
    sys.exit(app.exec_())


回答2:

The best way which I am thinking right now to solve this problem is to Create a class inherited from QApplication. Create a list inside this class and store references to all the newly created windows inside this list.

A minimal working example:

from PyQt4.QtGui import *
import sys

class Application(QApplication):
    def __init__(self, argv=None):
        super(Application, self).__init__(argv)
        self.windows = []
        win = Window(self)
        win.show()
        self.windows.append(win)

class Window(QMainWindow):
    def __init__(self, parentApp, parent=None):
        super(Window, self).__init__(parent)
        self.parentApp = parentApp
        btn = QPushButton("New Window", self)
        btn.clicked.connect(self.new)

    def new(self):
        win = Window(self.parentApp)
        win.show()
        self.parentApp.windows.append(win)

    def closeEvent(self, event):
        self.parentApp.windows.remove(self)


if __name__ == "__main__":
      app = Application(sys.argv)
      sys.exit(app.exec_())


回答3:

You can have many main windows without specifying the parent in PyQt without problem. Just run this code as an example:

from PyQt5 import QtWidgets
import sys

class MainWindow(QtWidgets.QMainWindow):
    pass

# App
q_app = QtWidgets.QApplication(sys.argv)

# Add many windows
main_window1 = MainWindow()
main_window1.show()
main_window2 = MainWindow()
main_window2.show()

# Run Qt app
sys.exit(q_app.exec_())

Note, for PyQt4, just replace QtWidgets with QtGui.



回答4:

I've never worked with UI in python but something seems wrong with this code:

The Main class ctor (from 1st code snippet) has 3 args: self, ctrl, and parent. Since parent is a default arg (it can be missing), it pretty much doesn't matter in our case.

The method code assuming we're in the same class: new_win = Main() is not correct. It should have 3 args:

  • the 3rd one was discussed
  • the 1st one(self) is automatically passed by python framework
  • the only thing it lacks is the 2nd one: ctrl and that must be supplied by yourself (after all, you defined the class ctor that way)