6

QListQMLから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);
    }
}
4

1 に答える 1

7

QObjectから派生したタイプ以外のタイプでQDeclarativeListProperty(またはQt5のQQmlListProperty)を使用することはできません。したがって、intまたはQStringは機能しません。

QStringListまたはQList、あるいはQMLでサポートされている基本タイプの1つの配列であるものを交換する必要がある場合、これを行う最も簡単な方法は、次のように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側では、NumberのJS配列に影響を与えるだけで、QMLエンジンが自動的にQVariantに変換して、Qtを理解できるようにします。

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

それで全部です !

于 2013-03-26T16:18:28.267 に答える