PyQt4 - “RuntimeError: underlying C/C object has b

2019-02-24 04:47发布

问题:

I keep getting this RuntimeError which I'm not sure how to fix. Here's what I'm trying to accomplish. I want to update this QTableWidget with values dynamically as I'm clicking on different items in my QTreeView. On the most part, my code works except when I click on my second item and I need to update my QTableWidgt which is when I run into this "RuntimeError: underlying C/C object has been deleted". Here's a snippet of my code:

def BuildTable( self ):
    ...
    for label in listOfLabels :
        attr = self.refAttr[label]
        self.table.setItem(row, 0, QtGui.QTableWidgetItem( label ) )

        tableItem = QtGui.QTableWidgetItem( str(attr.GetValue()) )
        self.table.setItem(row, 1, tableItem )
        someFunc = functools.partial( self.UpdateValues, tableItem, label )                     

        QtCore.QObject.connect(self.table, QtCore.SIGNAL('itemChanged(QTableWidgetItem*)'), someFunc)   

def UpdateValues(self, tableItem, label):
    print '--------------------------------'
    print 'UPDATING TEXT PROPERTY VALUE!!!'
    print tableItem.text()
    print label

The compiler complains errors on the line, "print tableItem.text()"

Thx!

回答1:

I believe the issue is that you are binding up a callback with a QTableWidget item and making many many connections (bad). Items can change. Thus, they can be deleted making your callback dead.

What you want is to just let the itemChanged signal tell you what item changed, the moment it happens.

self.table = QtGui.QTableWidget()
...
# only do this once...ever...on the init of the table object
QtCore.QObject.connect(
    self.table, 
    QtCore.SIGNAL('itemChanged(QTableWidgetItem*)'), 
    self.UpdateValues
)

And then in your SLOT, it will receive the item:

def UpdateValues(self, tableItem):
    print '--------------------------------'
    print 'UPDATING TEXT PROPERTY VALUE!!!'
    print tableItem.text()


标签: pyqt4