Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a python list of objects to qml

I am trying to pass a list of objects from python to qml. on the qml side, I will interpret this information and using repeater and listmodel element, display these information in a table like manner.

if i simply pass an object or a list of integers, i could read the information on the qml side. but otherwise when trying to pass a list of objects. how can i read a list of objects on the qml side? do i have to use different properties?

below is what i have so far:

class File(QObject):
    def __init__(self, fileName, commentsStatus, diagnosisStatus, parent=None):
        QObject.__init__(self, parent)
        self.fileName = fileName
        self.commentsStatus = commentsStatus
        self.diagnosisStatus = diagnosisStatus  

class DisplayComponent(QObject):
    def __init__(self, parent = None):
        QObject.__init__(self, parent)
        self.list = [File("file 1", True, False), File("file 2", False, True)]

    @pyqtProperty(QQmlListProperty)
    def getDicomFilesList(self):
        return QQmlListProperty(File, self, self.list)

exposing to the qml side the following way: context.setContextProperty("dicomFiles", displayComponent)

and this is how i am reading the list on the qml side:

HanaContainer {

    Text {
        id: display
        text: "no signal detected yet"
    }

    Component.onCompleted: {
        console.log(dicomFiles.getDicomFilesList[1]) // prints File(0x7f8a6d454c70)
        console.log(dicomFiles.getDicomFilesList[1].fileName) // prints undefined
    }
}

ps: am completely new to Qml and Qt5. if i am making any fundamental errors in my concepts, please do let me know

like image 942
eugeneoei Avatar asked Oct 18 '22 05:10

eugeneoei


1 Answers

For an attribute to be visible in qml this must be a property, for this you should use pyqtProperty as shown below:

class File(QObject):
    def __init__(self, fileName, commentsStatus, diagnosisStatus, parent=None):
        QObject.__init__(self, parent)
        self._fileName = fileName
        self._commentsStatus = commentsStatus
        self._diagnosisStatus = diagnosisStatus

    @pyqtProperty(str)
    def fileName(self):
        return self._fileName

    @pyqtProperty(bool)
    def commentsStatus(self):
        return self._commentsStatus

    @pyqtProperty(bool)
    def diagnosisStatus(self):
        return self._diagnosisStatus

The above will make the attribute only readable, if we want to be editable implementetar setters, eg:

@fileName.setter
def fileName(self, value):
    self._fileName = value
like image 172
eyllanesc Avatar answered Oct 27 '22 20:10

eyllanesc