pyqt5 關於主窗口閃退


窗口閃退

from PyQt5.QtWidgets import *
import sys


class Main(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("主窗口")
        button = QPushButton("彈出子窗口", self)
        button.clicked.connect(self.show_child)  # 關聯子窗口調用函數

    def show_child(self):
        child_window = Child()
        child_window.show()

class Child(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("子窗口")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Main()
    window.show()
    sys.exit(app.exec_())

程序中調用QDialog的show()方法,運行后點擊按鈕,子窗口會一閃而過,它的實例為父窗口show_child()方法中的局部變量,當窗口顯示后,父窗口的show_child()方法繼續執行,當方法運行完后,python的回收機制就把局部變量銷毀了,相當於子窗口實例被銷毀,故子窗口一閃而過。

將child_window改為類屬性就不會有這種問題

def show_child(self):
        self.child_window = Child()
        self.child_window.show()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM