如dant3所建议,将QObject与属性一起使用。
这是一个示例如何做:
import sysfrom PyQt4 import QtCore, QtGui, QtDeclarativefrom PyQt4.QtCore import pyqtProperty, pyqtSignal, QObjectclass TweetModel(QtCore.QAbstractListModel): def __init__(self, prototype, parent=None): QtCore.QAbstractListModel.__init__(self, parent) self.setRoleNames(prototype.roles) 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(QObject): roles = { QtCore.Qt.UserRole + 1: 'id', QtCore.Qt.UserRole + 6: 'original', } id_changed = pyqtSignal() def __init__(self, id=None, original=None, parent=None): QObject.__init__(self, parent=parent) self._data = {'original': original} self.id = id def data(self, key): return self._data[self.roles[key]] @pyqtProperty(str, notify=id_changed) def id(self): return self._data['id'] @id.setter def id(self, value): if self._data.get('id') != value: self._data['id'] = value self.id_changed.emit()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文件保持不变。
我没有
original建立属性,因为您可以将其作为模型数据来获取,但是可以按照与相同的方式进行创建
id。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)