PyQt5: multiple instances of same window

后端 未结 1 384
长发绾君心
长发绾君心 2020-12-12 04:34

I\'m having a problem with pyqt5. I have this piece of code to instantiate my class and open my window without closing after the show method (because gc).

de         


        
相关标签:
1条回答
  • 2020-12-12 05:28

    Explanation:

    To understand the problem, the following 2 codes and their outputs must be analyzed:

    Example1

    from PyQt5 import QtCore
    
    
    if __name__ == "__main__":
        app = QtCore.QCoreApplication([])
    
        o = QtCore.QObject()
        o.destroyed.connect(lambda: print("destroyed o"))
    
        o = QtCore.QObject()
    
        def on_timeout():
            print("quit")
            QtCore.QCoreApplication.quit()
    
        QtCore.QTimer.singleShot(1000, on_timeout)
    
        app.exec_()
    
    destroyed o
    quit
    

    Example2

    from PyQt5 import QtCore
    
    
    if __name__ == "__main__":
        app = QtCore.QCoreApplication([])
    
        o = QtCore.QObject()
        o.destroyed.connect(lambda: print("destroyed o"))
    
        p = o
    
        o = QtCore.QObject()
    
        def on_timeout():
            print("quit")
            QtCore.QCoreApplication.quit()
    
        QtCore.QTimer.singleShot(1000, on_timeout)
    
        app.exec_()
    
    quit
    destroyed o
    

    In the first example, the variable "o" is assigned a QObject and when another QObject is assigned, the initial QObject is deleted, so "destroyed" is printed before "quit".

    In the second example, it has the difference "p = o" where reference is made to the QObject, that is, in that line "p" and "o" represent the same object, so by assigning "or" a new QObject the initial QObject is not it destroys, and it is only destroyed when the loop ends and the GC does its job.

    That is what happens in your case in a subtle way, the logic of "p = o" is that the QObject is stored in another "place", and in your example that "place" is the lambda that has its own scope ( similarly with partial). Specifically, in your example, a new window was created destroying the previous one, causing a single window to be displayed at all times.

    Solution:

    One possible solution is to prevent the first window from being removed and a new window created using a flag:

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    flag = False
    
    # ...
    
    def open_otherwindow():
        global w, flag
        if not flag:
            w = OtherWindow()
            w.show()
        flag = True
    
    # ...
    0 讨论(0)
提交回复
热议问题