【发布时间】:2009-06-04 08:20:16
【问题描述】:
我是在 Qt 中使用模型/视图范例的菜鸟,并且有以下问题:我有一个树状结构,必须通过 Qt 可视化。我发现 QAbstractTableModel 非常适合我的需求,所以我写了以下内容:
class columnViewModel : public QAbstractTableModel {
// some stuff...
};
现在一切正常,但现在我必须在树的节点上实现“观察者”设计模式。每当节点在 TreeView 中展开时,我必须在相应的节点上添加一个观察者。每当节点崩溃时,我必须从节点中删除这个观察者。所以,我写了一些东西,像这样:
void onExpand( const QModelIndex & Index ... ) {
Node* myNode = static_cast<Node*>(Index->internalPointer());
Observer* foo = Observer::create();
myNode->addObserver(foo);
// ok up to here, but now where can I save this Observer? I must associate
// it with the Node, but I cannot change the Node class. Is there any way
// to save it within the index?
}
void onCollapse( const QModelIndex & Index ... ) {
Node* myNode = static_cast<Node*>Index->internalPointer();
Observer* foo = // well, what should I write here? Node does not have anything
// like "getObserver()"! Can I extract an Observer from Index?
myNode->remObserver( foo );
}
我现在没有 sn-ps,所以代码可能不是有效的 Qt,但问题似乎很清楚。我既不能改变 Node 也不能改变 Observer 类。我可以有一个观察者的内部列表,但是我必须解决从特定节点中删除的观察者。有什么方法可以将 Observer 指针保存在 Index 中(可能是一些用户数据),以便在 onCollapse 中快速解决它?欢迎任何想法......
【问题讨论】: