2017-10-13 85 views
0

我有一個QML表示從數據庫獲取值的計劃,因此我需要從我的Python代碼中插入值到ListModel。 QML看起來像這樣:使用PyQt將項目設置爲QML ListModel動態模式

​​

我一個功能,應該插入值QML的ListModel:

class ScheduleView(QObject): 
    def __init__(self, parent=None): 
     QObject.__init__(self, parent=parent) 
     self._presenter = SchedulePresenter(self) 
     self._widget = QQuickWidget(parent) 
     self._widget.rootContext().setContextProperty('scheduleView', self) 
     self._widget.rootContext().setContextProperty('groupsModel', self) 
     self._widget.setSource(QUrl('modules/schedule/Form.qml')) 

def reprSchedules(self): 
    values = [{"lesson": "1", "subject": "PE", "day": "Monday"}, 
       {"lesson": "2", "subject": "PE", "day": "Monday"}, 
       {"lesson": "3", "subject": "PE", "day": "Monday"}] 
    #model = self._widget.rootObject().findChild(QObject, "scheduleModel") 

我沒有任何想法如何做到這一點。請問你能幫幫我嗎?我使用的是Python2.7,PyQt5.9,QtQuick2.5

回答

1

對於這個任務,你可以調用您在通過QMetaObject.invokeMethod()的.qml實施了追加的功能,如下圖所示:

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 
      } 
    } 
} 

共完整的例子可以在下面找到link