我正在写一个 Twitter 客户端。我实施了TweetItem
和TweetModel
. TweetItem
问题是在被调用的中有一个角色original
。我希望它指向原始推文。
更新:我的代码中有一些错字。现在我修好了它们。
import sys
from PyQt4 import QtCore, QtGui, QtDeclarative
class TweetModel(QtCore.QAbstractListModel):
def __init__(self, prototype, parent=None):
QtCore.QAbstractListModel.__init__(self, parent)
self.setRoleNames(prototype.roleNames())
self.tweets = []
def appendRow(self, item):
self.tweets.append(item)
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.tweets)
def data(self, index, role):
return self.tweets[index.row()].data(role)
class TweetItem(QtCore.QAbstractItemModel):
def __init__(self, id=None, original=None, parent=None):
QtCore.QAbstractItemModel.__init__(self, parent)
self.idRole = QtCore.Qt.UserRole + 1
# More Roles
self.originalRole = QtCore.Qt.UserRole + 6
self.id = id
self.original = original
def roleNames(self):
names = {}
names[self.idRole] = "id"
names[self.originalRole] = "original"
return names
def data(self, role):
if role == self.idRole:
return self.id
elif role == self.originalRole:
# self.original == <__main__.TweetItem object at 0x7fb703d95d40>
return self.original
else:
return None
if __name__ == "__main__":
model = TweetModel(TweetItem())
item = TweetItem("0001", None, model)
model.appendRow(TweetItem("0002", item, model))
App = QtGui.QApplication(sys.argv)
view = QtDeclarative.QDeclarativeView()
view.rootContext().setContextProperty("mymodel", model)
view.setSource(QtCore.QUrl.fromLocalFile("main.qml"))
view.show()
App.exec_()
但我不能在 QML 中使用它。我得到一个undefined
值。
import QtQuick 1.0
Rectangle {
width: 360
height: 360
ListView {
anchors.fill: parent
model: mymodel
// original.id == undefined
delegate: Component { Text { text: id + " " + original.id } }
}
}
那么,是否可以在 a 中返回一个对象role
并使用它?