访问QML中的QList对象

Access QList object in QML

本文关键字:对象 QList 中的 QML 访问      更新时间:2023-10-16

自从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>,为什么?我做错了什么

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

存储.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);
};

存储.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公开类似列表的属性。要提供列表属性,C++类必须实现操作回调,然后从属性getter返回适当的QQmlListProperty值。列表属性不应具有setter。当用C++代码扩展QML时,可以向QML类型系统注册C++类,以使该类能够用作QML代码中的数据类型。

您是否将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