在QML中访问QList对象

时间:2015-11-10 11:04:31

标签: javascript c++ qt qml

自从Javascript以来我访问QList对象时遇到了一些问题。我有一个C ++类,允许我从QML / JS开始执行SQL查询。一切正常,我用C ++得到了我的结果。

我的问题是我向QML返回了一个QList对象。 这是我在C ++中返回SQL结果的函数(注意是一个具有不同属性的简单对象):

QList<Note> Storage::setQuery(QString query)
{
    QList<Note> noteItems;
    QSqlQuery qsqlQuery;
    bool ok = qsqlQuery.exec(query);
    if(!ok)
    {
        qDebug() << "Error setQuery" << m_sqlDatabase.lastError();
    }
    else
    {

        while (qsqlQuery.next()) {
            Note my_note;
            QString note = qsqlQuery.value("message").toString();
            my_note.setMessage(note);

            noteItems.append(my_note);
        }
   }

   return noteItems;
}

但是当我从JS调用此函数时,我收到此错误:Unknown method return type: QList<Note> 问题是返回类型,QML JS不知道类型QList<Object>,为什么?我做错了什么

2 个答案:

答案 0 :(得分:2)

如果你想在Qml中使用c ++ QList作为模型,我建议你使用以下程序。我使用自己的例子,你可以根据自己的需要改变它。

<强> storage.h定义

class Storage : public QObject {
    Q_PROPERTY(QQmlListProperty<Note> getList READ getList)

public:
    QQmlListProperty<Note> getList();
    void setQuery(QString query);
    QList<Note> noteItems;;
private:
    static void appendList(QQmlListProperty<Note> *property, Note *note);
    static Note* cardAt(QQmlListProperty<Note> *property, int index);
    static int listSize(QQmlListProperty<Note> *property);
    static void clearListPtr(QQmlListProperty<Note> *property);
};

<强> Storage.cpp

void Field::appendList(QQmlListProperty<Card> *property, Note *note) {
    Q_UNUSED(property);
    Q_UNUSED(note);
}

Note* Field::cardAt(QQmlListProperty<Note> *property, int index) {
    return static_cast< QList<Note> *>(property->data)->at(index);
}

int Field::listSize(QQmlListProperty<Note> *property) {
    return static_cast< QList<Note> *>(property->data)->size();
}
void Field::clearListPtr(QQmlListProperty<Note> *property) {
    return static_cast< QList<Note> *>(property->data)->clear();
}

QQmlListProperty<Note> Field::getList() {
    return QQmlListProperty<Note>( this, &list[0], &appendList, &listSize, &cardAt,  &clearListPtr );
}

void Storage::setQuery(QString query)
{
    QList<Note> noteItems;
    QSqlQuery qsqlQuery;
    bool ok = qsqlQuery.exec(query);
    if(!ok)
    {
        qDebug() << "Error setQuery" << m_sqlDatabase.lastError();
    }
    else
    {

        while (qsqlQuery.next()) {
            Note my_note;
            QString note = qsqlQuery.value("message").toString();
            my_note.setMessage(note);

            noteItems.append(my_note);
        }
   }
}

<强>的main.cpp

int main(int argc, char *argv[])
{
    qmlRegisterType<Note>();
}

QQmlListProperty类允许应用程序向QML公开类似列表的属性。要提供list属性,C ++类必须实现操作回调,然后从属性getter返回适当的QQmlListProperty值。列表属性应该没有setter。使用C ++代码扩展QML时,可以使用QML类型系统注册C ++类,以使该类能够用作QML代码中的数据类型。

答案 1 :(得分:1)

您是否将Note注册为元类型?可能是缺少的东西:

http://doc.qt.io/qt-5/qmetatype.html#Q_DECLARE_METATYPE

在Qt 4中,您还必须注册QList<Note>,但不能注册Qt 5。

哦,Note应该是Q_GADGET,否则您也无法从QML访问其内容。确保使用Qt 5.5+。否则,您需要QList<Note*>并使这些Note个对象继承自QObject

相关问题