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

时间:2012-12-19 10:29:08

标签: c++ qt qml qt-quick

我正在尝试将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);
    }
}

1 个答案:

答案 0 :(得分:7)

您不能将QDeclarativeListProperty(或Qt5中的QQmlListProperty)与除QObject派生类型之外的任何其他类型一起使用。所以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];

这就是全部!