【发布时间】:2017-01-11 13:18:11
【问题描述】:
我尝试重新实现QSortFilterProxyModel 的filterAcceptsRow(int source_row, const QModelIndex &source_parent)-方法。
这里我想调用一个可调用的QJSValue 并将两个参数传递给它。为此,我需要将它们放在QJSValueList 中,这对于整数来说很容易。
但我找不到对QModelIndex 执行相同操作的方法。
- 没有
JSValue的构造函数接受QModelIndex -
QJSEngine::createQObject接受一个我没有的 QObject。
我有成功的机会吗?
编辑:我现在尝试了什么
bool FilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
if (m_filter.isCallable()) { // check whether a JS-Function is set
QJSValueList l;
QJSValue f = QJSValue(m_filter);
l << QJSValue(source_row);
// **** ADD MORE USEFULL STUFF HERE ****
// This is working now - thanks to your help. But useless in QML
QJSEngine *engine = m_filter.engine();
l << engine->toScriptValue(source_parent);// <-- Value is of no use in QML. Can't do anything with it. And for ListModels as source utterly useless
// V----- To add this would make more sense, but the app crashes. Don't call index()!!!
// l << engine->toScriptValue(index(source_row, 0, source_parent));
return f.call(l).toBool();
}
// If no JS-Function is set, fall back to the original method
return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
}
请原谅我任何微不足道的错误。距离我上次使用(并开始学习)C++ 已有 5 年了。
【问题讨论】:
-
QModelIndex直接在DelegateModel中使用,这意味着您应该能够将其包装在QVariant中。 -
是的,可以将其包装在
QVariant中,但我仍然无法从中获得QJSValue。也没有toQJSValue()或QJSValue-构造函数接受QVariant。QVariant也不是QObject,所以还是不能传给QJSEngine::createQObject-factory。 -
为什么?你打算用它做什么?您只能将 QJSValue 用于 QObject 引用和原始类型。不需要更多。
-
好吧,您总是可以编写自己的转换函数来创建一个包含所需模型索引成员的 JS 对象。从外观上看,模型索引是 QML 中的一种不透明类型——你可以传递它,但它不能直接从 JS 代码中使用。所以你必须手动转换。
-
我还在我仍然未充分测试和记录不足的库 github.com/oKcerG/SortFilterProxyModel 中实现了它。用法为
filters: ExpressionFilter { expression: /* an expression that evaluates to a bool. You can access roles and index here like in a delegate */ }
标签: javascript c++ qt qml