在 Python 中返回一个角色中的对象并在 QML 中获取另一个对象的引用 [英] Return an object in a role in Python and get a reference of another object in QML
问题描述
我正在编写一个 Twitter 客户端.我实现了 TweetItem
和 TweetModel
.问题在于 TweetItem
中有一个名为 original
的角色.我希望它指向原始推文.
I'm writing a Twitter client. I implemented TweetItem
and TweetModel
. The issue is that there is a role in TweetItem
called original
. I want it to point to the original tweet.
更新:我的代码中有一些拼写错误.现在我修复了它们.
Update: There were some typo in my code. Now I fixed them.
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
值.
But I can not use it in QML. I get an undefined
value.
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 } }
}
}
那么,是否可以在 role
中返回一个对象并使用它?
So, is it possible to return an object in a role
and use it?
推荐答案
正如 dant3 所建议的那样使用 QObject 和属性.
As was suggested by dant3 use QObject with properties.
这是一个如何做的例子:
Here is an example how to do it:
import sys
from PyQt4 import QtCore, QtGui, QtDeclarative
from PyQt4.QtCore import pyqtProperty, pyqtSignal, QObject
class 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 文件保持不变.
The QML file remains the same.
我没有将 original
设为属性,因为您将其作为模型数据获取,但是您可以以与 id
相同的方式创建它.
I didn't make original
a property, since you get it as model data, but you can make it in the same fashion as id
.
这篇关于在 Python 中返回一个角色中的对象并在 QML 中获取另一个对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!