How to create a new window button PySide/PyQt?

后端 未结 2 605
你的背包
你的背包 2021-01-13 18:46

I\'m having problems with a \"New Window\" function in PyQt4/PySide with Python 2.7. I connected a initNewWindow() function, to create a new window, to an actio

2条回答
  •  天涯浪人
    2021-01-13 19:24

    If a function creates a PyQt object that the application needs to continue using, you will have to ensure that a reference to it is kept somehow. Otherwise, it could be deleted by the Python garbage collector immediately after the function returns.

    So either give the object a parent, or keep it as an attribute of some other object. (In principle, the object could also be made a global variable, but that is usually considered bad practice).

    Here's a revised version of your example script that demonstrates how to fix your problem:

    from PySide import QtGui, QtCore
    
    class Window(QtGui.QMainWindow):
        def __init__(self):
            QtGui.QMainWindow.__init__(self)
            menu = self.menuBar().addMenu(self.tr('View'))
            action = menu.addAction(self.tr('New Window'))
            action.triggered.connect(self.handleNewWindow)
    
        def handleNewWindow(self):
            window = QtGui.QMainWindow(self)
            window.setAttribute(QtCore.Qt.WA_DeleteOnClose)
            window.setWindowTitle(self.tr('New Window'))
            window.show()
            # or, alternatively
            # self.window = QtGui.QMainWindow()
            # self.window.setWindowTitle(self.tr('New Window'))
            # self.window.show()
    
    if __name__ == '__main__':
    
        import sys
        app = QtGui.QApplication(sys.argv)
        window = Window()
        window.resize(300, 300)
        window.show()
        sys.exit(app.exec_())
    

提交回复
热议问题