[英]Access QList object in 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>
,為什么? 我做錯了什么
如果你想在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
代碼中的數據類型。
您是否將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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.