Passing a python list of objects to qml

你。 提交于 2020-01-03 15:36:31

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/46387666/passing-a-python-list-of-objects-to-qml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!