我正在尝试从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*'
答案 0 :(得分:2)
由于没有人回答这个问题,我建议您使用解决方法: 使用两个参数在qml中创建一个javascript函数,并从QML文件中将元素添加到表中。
(显然你必须先从python中调用这个函数,但这只是一块蛋糕......)
P.S。如果您想展示示例,请在评论中告诉我:]
编辑:已添加代码
import QtQuick 2.3
import MyApplication 1.0
QPythonBinding{
id: binding
signal addElement(string param1, string param2)
onAddElement: {
myModel.append({"key1" : param1, "key2" : param2})
}
}
现在是python代码
class QPythonBinding(QQuickItem):
def __init__(self, parent=None):
super(QPythonBinding, self).__init__(parent)
addElement = pyqtSignal(str, str) #you call it like this - addElement.emit("name", "value")
if __name__ == '__main__':
import sys
app = QGuiApplication(sys.argv)
qmlRegisterType(QPythonBinding, "MyApplication", 1, 0, "QPythonBinding")
view = QQuickView()
view.show()
app.exec_()