Qt 获取 QStandardItemModel 的自定义数据类型的引用来更改它
这变得有点奇怪,我看不到实际更改 QStandardItemModel 的“数据”的方法。例如:
struct TestStruct {
std::vector<int> testVector;
void addNumber(int i){
//this method will modify the member vector
}
};
Q_DECLARE_METATYPE(TestStruct)
QStandardItemModel* model = QStandardItemModel(1,1);
QModelIndex index = model->index(0,0);
TestStruct test;
test.addNumber(1);
model->setData(index, qVariantFromValue(test));
这样,我就可以有效地将一个编号为 1 的 std::vector 添加到模型的索引 {0,0} 中。但是,如何从无法再访问 TestStruct 实例的位置向该 TestStruct 向量添加另一个数字呢?
“data”函数返回一个可以转换为 TestStruct 的 QVariant,但它是一个副本,我需要一个引用......明白了吗?
It's getting a little weird I can't see a method to actually change the "data" of a QStandardItemModel. For example:
struct TestStruct {
std::vector<int> testVector;
void addNumber(int i){
//this method will modify the member vector
}
};
Q_DECLARE_METATYPE(TestStruct)
QStandardItemModel* model = QStandardItemModel(1,1);
QModelIndex index = model->index(0,0);
TestStruct test;
test.addNumber(1);
model->setData(index, qVariantFromValue(test));
With that, I will effectively have added a std::vector with the number 1 to the index {0,0} of the model. But how would I add another number to that TestStruct's vector from places that don't have access to the TestStruct instance anymore?
The "data" function returns a QVariant that can be casted as a TestStruct but it's a copy and I need a reference... get it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,它只会返回值,而不返回引用。
解决此问题的方法是,您可以通过对
QVariant
进行类型转换来获取struct
。然后修改您的testVector
。修改后,再次调用,
其中
newTest
是带有修改后的 Vector 的struct
。希望有帮助。
Yes it will return the value only and not it's reference.
A workaround for this is, you can get the
struct
by Typecasting theQVariant
. Then modify yourtestVector
.After modifications, call again
where
newTest
is yourstruct
with the modified Vector.Hope it helps.