Search code examples
c++qtqscript

How to return QList<double> from QObject-based class method for use in Qt Script


I am developing an application in Qt that uses the QScript module. The class I am working on is derived from QObject so that it will be "scriptable". One of the methods should return a list of double values (QList). When I create a global script object with one instance of the class, using engine.newQObject(class_instance)), I can access a number of methods of the script object perfectly fine, showing that the process is working. I can call from the script a method that returns a double, but the function that should return the QList remains silent.

Any idea how I could implement the C++ class' method such that it would faithfully return that list of double values ?

Code:

Class code (QCustomPlot is derived from QWidget)

class AbstractPlotWidget : public QCustomPlot
    {
        Q_OBJECT;

Function meant to return a list of double values:

(declared as Q_INVOKABLE)

QList<double> 
        AbstractPlotWidget::keys()
        {
            QList<double> keyList;

            QCPDataMap *data = graph()->data();

            return data->keys();
        }

When I run that function, all I get in the script console is: QVariant(QList)

I crafted the following test function that returns a QStringList representing the double value list:

(declared as Q_INVOKABLE)

QStringList
    AbstractPlotWidget::keysAsStringList()
    {
        QStringList keyStringList;

        QCPDataMap *data = graph()->data();

        QList<double> keyList = data->keys();

        for(int iter = 0; iter < keyList.size(); ++iter)
        {
            double keyValue = keyList.at(iter);

            keyStringList.append(QString("%1\n").arg(keyValue));
        }

        return keyStringList;
    }

And when I run that function, the script console effectively shows the text with the comma-separated double values.

I also wrote a simple function returning a single double value and that works also. Another test function return a QList<int> works.

So I guess, there is no autoconversion between QList<double> and a corresponding script value. It looks like I need a way to have the QScriptEngine instance know how to convert QList<double> to a Qt Script variable.

Thanks


Solution

  • You need to register the type. See here

    (TL,DR: use

    qScriptRegisterSequenceMetaType< QList<double> >(_engine);
    

    where _engine is a QScriptEngine. A good time to register is on creation of the engine. )

    Because it's a standard container type, that's pretty much all you need to do.

    With more complex types (e.g. your own classes) you use qScriptRegisterMetaType and provide custom functions to translate to and from the engine environment.