Set items to QML ListModel dynamicaly with PyQt

前端 未结 1 521
难免孤独
难免孤独 2021-01-25 02:33

I have a QML that represent schedule, that get values from database, so I need insert values to ListModel from my python code. QML looks like that:

         


        
相关标签:
1条回答
  • 2021-01-25 02:58

    For this task you can invoke the append function that you have implemented in the .qml through QMetaObject.invokeMethod() as shown below:

    main.py

    counter = 0
    
    def onTimeout(obj):
        global counter
        value = {"lesson": str(counter), "subject": "PE", "day": QDate.longDayName(1 + counter % 7)}
        QMetaObject.invokeMethod(obj, "append", Q_ARG(QVariant, value))
        counter += 1
    
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        w = QQuickWidget()
        w.setSource(QUrl('main.qml'))
        timer = QTimer()
        timer.timeout.connect(lambda: onTimeout(w.rootObject()))
        timer.start(1000)
        w.show()
        sys.exit(app.exec_())
    

    main.qml

    import QtQuick 2.0
    
    Rectangle {
        width: 640
        height: 480
    
        function append(newElement) {
            scheduleModel.append(newElement)
        }
        ListModel {
            id: scheduleModel
        }
    
        ListView {
            anchors.fill: parent
            id: scheduleList
            model: scheduleModel
            delegate: scheduleItem
    
            section.property: "day"
            section.delegate: sectionDelegate
        }
    
    
        Component {
            id: scheduleItem
                Row {
                    spacing: 15
                    Text {
                        text: lesson
                    }
                    Text {
                        text: subject
                    }
            }
        }
    
        Component {
            id: sectionDelegate
                Text {
                    id: label
                    text: section
                }
        }
    }
    

    The complete example can be found at the following link

    0 讨论(0)
提交回复
热议问题