Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Python QObject from QML fails to convert on second call

Tags:

python

qt

pyqt

qml

I am hitting an obscure problem (bug?) with my Python3 QML program. I implemented a QAbstractListModel with a custom get method to get to the underlying QObject items. The moment I try to get the same Python QObject at two different places in QML I get:

TypeError: unable to convert a Python 'QMyItem' object to a C++ 'QObject*' instance

The get method looks like this:

@pyqtSlot(int, result=QMyItem)
def get(self, row):
    return self._items[row]

And the model like this:

ComboBox {
    model: mymodel
    textRole: 'name'
    onActivated: mymodel.item = model.get(index)
    onModelChanged: currentIndex = getCurrentIndex(mymodel, mymodel.item)
}

The problem is actually unrelated to the way I retrieve the QObject. It really seems to be about the Python to QML conversion. As if the converter keeps a list of already passed references and gets out of sync somehow.

I now have a minimal sample which shows the error. Get the source from https://github.com/sturmf/python_samples.git and go into the folder pyqt_combobox_qabstractlistmodel. In there start the sample with python3 main.py. In the shown ComboBox see that you can select item three but item one gives you an error on the console. The reason is that item one was already once passed from Python to QML and it doesn't work a second time.

Maybe the converted QObject got somehow garbage collected on the QML side?

like image 353
Fabian Avatar asked May 16 '16 15:05

Fabian


1 Answers

So the problem was that the QML side garbage collected my objects after I handed them to QML. The reason is that I never set a parent fot this QObjects.

like image 98
Fabian Avatar answered Sep 20 '22 13:09

Fabian