我试图从python函数中获取一个字符串回QML。它似乎适用于下面的一个简单的Text项,其中'value
'属性取自python函数MyDB.getIncome()
。这很好用。但是,当我使用相同的功能但填充ListElement
的属性时,它似乎无法正常工作。
下面的第一个main.qml工作正常。
附加的第二个main.qml是一个不能工作的。如果你想尝试其他所有工作只是注释掉'属性字符串值:myDB.getIncome()'并为它赋值一些
main.py
import sys
from PyQt5.QtCore import QUrl, QObject, pyqtSlot, pyqtSignal, pyqtProperty, QVariant
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView
class MyDB(QObject):
def __init__(self):
super().__init__()
@pyqtSlot(result=str)
def getIncome(self):
return "testing income"
## Main Function
if __name__ == '__main__':
myApp = QApplication(sys.argv)
appLabel = QQuickView()
mydb = MyDB()
appLabel.rootContext().setContextProperty("myDB", mydb)
appLabel.setSource(QUrl('main.qml'))
appLabel.show()
myApp.exec_()
sys.exit()
main.qml(工作正常)
import QtQuick 2.2
Rectangle {
id: root
width: 250; height: 450
color: "gray"
Text {
id: exp
anchors.centerIn: parent
color: 'dark red'
horizontalAlignment: Text.AlignHCenter
font.pixelSize: 18
property string value: myDB.getIncome()
text: value
}
}
main.qml(不工作)
import QtQuick 2.0
Rectangle {
id: root
width: 250; height: 450
color: "white"
ListModel {
id: mainModel
ListElement {
name: "Money"
//property string value: 3
property string value: myDB.getIncome()
}
ListElement {
name: "Total Expenses"
property string value: 4
}
ListElement {
name: "Total Income"
property string value: 56
}
}
Component {
id: mainDelegate
Item {
width: 100; height: 100
scale: PathView.iconScale
Image {
id: myIcon
y: 20; anchors.horizontalCenter: parent.horizontalCenter
source: icon
}
Text {
anchors { top: myIcon.bottom; horizontalCenter: parent.horizontalCenter }
font.pixelSize: 18
text: name + ": " + value
}
MouseArea {
anchors.fill: parent
}
}
}
Component {
id: appHighlight
Rectangle { width: 130; height: 10; color: "lightsteelblue" }
}
PathView {
id: view
anchors.fill: parent
highlight: appHighlight
preferredHighlightBegin: 0.5
preferredHighlightEnd: 0.5
focus: true
model: mainModel
delegate: mainDelegate
path: Path {
startX: root.width/2
startY: 0
PathAttribute { name: "iconScale"; value: 0.5 }
PathLine { x: root.width/2; y: root.height*0.4; }
PathPercent { value: 0.48; }
PathLine { x: root.width/2; y: root.height*0.5; }
PathAttribute { name: "iconScale"; value: 1.0 }
PathLine { x: root.width/2; y: root.height*0.6; }
PathPercent { value: 0.52; }
PathLine { x: root.width/2; y: root.height; }
PathAttribute { name: "iconScale"; value: 0.5 }
}
}
}