如何将QList从QML传递到C++/Qt?

6
我正在尝试将整数类型的QList从QML传递到C++代码中,但是我的方法似乎不起作用。使用以下方法时,我遇到了以下错误:
left of '->setParentItem' must point to class/struct/union/generic type
type is 'int *'

任何帮助解决问题的意见都非常感激。
以下是我的代码片段。 头文件
Q_PROPERTY(QDeclarativeListProperty<int> enableKey READ enableKey) 

QDeclarativeListProperty<int> enableKey(); //function declaration
QList<int> m_enableKeys;

cpp文件

QDeclarativeListProperty<int> KeyboardContainer::enableKey()
{
    return QDeclarativeListProperty<int>(this, 0, &KeyboardContainer::append_list);
}

void KeyboardContainer::append_list(QDeclarativeListProperty<int> *list, int *key)
{
    int *ptrKey = qobject_cast<int *>(list->object);
    if (ptrKey) {
        key->setParentItem(ptrKey);
        ptrKey->m_enableKeys.append(key);
    }
}

2
setParentItemm_enableKeys不是int的成员,但您尝试在keyptrKey上调用它们,它们都是int*,所以这永远不会起作用。 - stijn
请记住,QDeclarativeListProperty / QQmlListProperty 仅适用于提供只读的子项列表,这些子项是 QObject 派生的对象,并且该列表在实例化后无法修改。 - TheBootroo
1个回答

7

如果您想在Qt中使用QML,必须使用QObject派生类型,否则无法使用QDeclarativeListProperty(或Qt5中的QQmlListProperty)。因此,int或QString将永远不起作用。

如果您需要交换QStringList或QList或任何是QML支持的基本类型数组,请在C++端使用QVariant是最简单的方法,例如:

#include <QObject>
#include <QList>
#include <QVariant>

class KeyboardContainer : public QObject {
    Q_OBJECT
    Q_PROPERTY(QVariant enableKey READ   enableKey
               WRITE  setEnableKey
               NOTIFY enableKeyChanged)

public:
    // Your getter method must match the same return type :
    QVariant enableKey() const {
        return QVariant::fromValue(m_enableKey);
    }

public slots:
    // Your setter must put back the data from the QVariant to the QList<int>
    void setEnableKey (QVariant arg) {
        m_enableKey.clear();
        foreach (QVariant item, arg.toList()) {
            bool ok = false;
            int key = item.toInt(&ok);
            if (ok) {
                m_enableKey.append(key);
            }
        }
        emit enableKeyChanged ();
    }

signals:
    // you must have a signal named <property>Changed
    void enableKeyChanged();

private:
    // the private member can be QList<int> for convenience
    QList<int> m_enableKey;
};     

在QML侧,只需影响一个数字的 JS 数组, QML 引擎会自动将其转换为 QVariant 以使其能被 Qt 理解:

KeyboardContainer.enableKeys = [12,48,26,49,10,3];

这是所有的内容!

但是...这个文档怎么办?http://qt-project.org/doc/qt-5.0/qtqml/qtqml-cppintegration-data.html - S.M.Mousavi
1
在上述文档中,QList<int>、QListString、QList<QString>以及其他一些序列都有透明的支持。 - S.M.Mousavi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接