【发布时间】:2016-07-05 17:47:15
【问题描述】:
我正在尝试从 Python 向表中添加行。我正在使用 QML 描述的 TableView。
我不知道如何将模型添加到表中,除非该模型也在 QML 中。但我不知道如何为模型添加值。
import sys
from PyQt5.QtCore import QAbstractTableModel, QObject, QUrl
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtQuick import QQuickView
from PyQt5.QtWidgets import QApplication
myApp = QApplication(sys.argv)
engine = QQmlApplicationEngine()
context = engine.rootContext()
context.setContextProperty("main", engine)
engine.load('users.qml')
mainWin = engine.rootObjects()[0]
# Add items
userTable = mainWin.findChild(QObject, "userTable")
tableModel = mainWin.findChild(QObject, "libraryModel")
tableModel.setData(tableModel.index(0), "one")
tableModel.setData(tableModel.index(1), "one")
mainWin.show()
sys.exit(myApp.exec_())
users.qml
import QtQuick 2.3
import QtQuick.Controls 1.2
ApplicationWindow {
ListModel {
id: libraryModel
objectName: "libraryModel"
ListElement {
title: "A Masterpiece"
author: "Gabriel"
}
ListElement {
title: "Brilliance"
author: "Jens"
}
ListElement {
title: "Outstanding"
author: "Frederik"
}
}
TableView {
objectName: "userTable"
anchors.fill: parent
TableViewColumn {
role: "title"
title: "Title"
}
TableViewColumn {
role: "author"
title: "Author"
}
model: libraryModel
}
}
编辑
tableModel.append({'author': 'one', 'title': 'two'})
builtins.TypeError: unable to convert argument 0 of
QAbstractListModel.append from 'dict' to 'QQmlV4Function*'
【问题讨论】:
-
为什么不用
ListModel类型的append方法呢? (doc.qt.io/qt-5/qml-qtqml-models-listmodel.html#append-method) -
“我不知道如何将模型添加到表中,除非该模型也在 QML 中。但我不知道如何为模型添加值。”对不起,什么?什么是模型类型,你想在哪里定义它,你想从哪一侧操作它?