2013-07-29 49 views
8

如果我運行此代碼:PyQt的:RuntimeError:包裝的C/C++對象已被刪除

#!/usr/local/bin/ python3 

import sys 
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 


class Window(QMainWindow): 

    def __init__(self): 
     super().__init__() 
     self.button1 = QPushButton("1") 
     self.button2 = QPushButton("2") 
     self.setCentralWidget(self.button1) 
     self.button1.clicked.connect(lambda: self.setCentralWidget(self.button2)) 
     self.button2.clicked.connect(lambda: self.setCentralWidget(self.button1)) 
     self.show() 

if __name__ == '__main__': 

    import sys 
    app = QApplication(sys.argv) 
    window = Window() 
    sys.exit(app.exec_()) 

...我得到這樣的輸出:

Traceback (most recent call last): 
    File "test.py", line 16, in <lambda> 
    self.button2.clicked.connect(lambda: self.setCentralWidget(self.button1)) 
RuntimeError: wrapped C/C++ object of type QPushButton has been deleted 

我不明白爲什麼對象正在被刪除。窗口應該保持對它的引用。 我已經徹底調查這些職位: Understanding the 「underlying C/C++ object has been deleted」 error Can a PyQt4 QObject be queried to determine if the underlying C++ instance has been destroyed?

爲何按鈕被刪除?

+1

我在QWidget的子類中遇到了類似的問題,事實證明問題是我忘記了在我的'__init__'開始時調用QWidget的'__init__'。調皮。 – spookypeanut

回答

9

這回答這個問題,是因爲在這裏找到: Python PySide (Internal c++ Object Already Deleted)

顯然,分配一個小部件使用setCentralWidget到QMainWindow中,然後分配與setCentralWidget另一小會造成底層C++ QWidget中被刪除,即使我有一個保持對它的引用的對象。

Note: QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time.

0

大腦的回答完全說明問題。 This Link更詳細地解釋事情。

我對這個問題的解決方案是將窗口小部件設置爲對象的屬性(例如,只需在您的類方法中使用self.label = ...而不是label = ...)。您可能想要爲附件上的任何佈局執行相同的操作。

通過這種方式,您可以創建小部件的副本,以便在發生C++內存清理時仍可引用小部件。

希望這會有所幫助。

相關問題