2012-12-19 72 views
6

我试图通过从QML到C++代码的整数QList,但不知何故我的方法不起作用。下面的方法我收到以下错误:如何将QList从QML传递到C++/Qt?

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

'setParentItem'和'm_enableKeys'不是'int'的成员,但是您尝试在key和ptrKey上调用它们,它们都是int *,因此它们将永远不会工作。 – stijn

+0

请记住'QDeclarativeListProperty' /'QQmlListProperty'仅用于提供QObject派生子对象的只读列表,并且该实例在实例化之后不能被修改。 – TheBootroo

回答

7

不能在QObject派生的类中使用QDeclarativeListProperty(或Qt5中的QmlmlListProperty)。所以int或QString永远不会工作。

如果您需要交换一个QStringList中或的QList或任何是QML,要做到这一点是使用的QVariant在C++方面,这样最简单的方法支持的基本类型之一的数组:

#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]; 

这一切!

+0

但是......这个文件呢? http://qt-project.org/doc/qt-5.0/qtqml/qtqml-cppintegration-data.html –

+1

在上面的文档中,对QList 和QListString和QList 以及其他一些序列 –