简体   繁体   中英

QModelIndex to QJSValue

I try to reimplement the filterAcceptsRow(int source_row, const QModelIndex &source_parent) -method of a QSortFilterProxyModel .

Here I want to call a callable QJSValue and pass the two parameters to it. For this I need to have them in a QJSValueList , which is easy for the integer.

But I fail to find the method to do the same with the QModelIndex .

  • There is no constructor of the JSValue that takes a QModelIndex
  • QJSEngine::createQObject takes a QObject, which I don't have.

Do I have any chance on succeeding?

EDIT: WHAT I TRIED NOW

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);
}

Please forgive me any trivial errors. Its 5 years since I last used (and started to learn) C++.

I'm not quite sure what you're doing from your description, but assuming you have a QModelIndex (in C++) and want a QJSValue for some reason, then I think QJSEngine::toScriptValue is indeed what you want. This should probably be linked from the QJSValue doc, I'll try fix that for a future release.

I've never done this myself, but something like this should work:

QJSEngine *e; /* I assume you've got this already somewhere .. */
QModelIndex m = something->index(...); /* and you have a model index */
QJSValue val = e->toScriptValue(m);
// go ahead and use val!

If you want to go the other direction, that is, unboxing a QModelIndex from a QJSValue:

QJSValue val = something->prop(); // now to extract it...
QModelIndex m = e->fromScriptValue<QModelIndex>(val);
// go ahead and use m!

Both QVariant and QJSValue are sort of dynamic "boxes" that can contain different types of data, so you don't want to double up and give QML what amounts to QJSValue(QVariant(QModelIndex)) (won't compile, just to demonstrate storage), because it won't know how to unbox it properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM