DNa*_*mto 6 c++ qt qml qt-quick
我正在尝试将QListQML中的整数传递给C++代码,但不知怎的,我的方法无效.使用以下方法我得到以下错误:
left of '->setParentItem' must point to class/struct/union/generic type
type is 'int *'
Run Code Online (Sandbox Code Playgroud)
任何麻烦拍摄问题的输入都非常感谢
以下是我的代码段
头文件
Q_PROPERTY(QDeclarativeListProperty<int> enableKey READ enableKey)
QDeclarativeListProperty<int> enableKey(); //function declaration
QList<int> m_enableKeys;
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
您不能将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;
};
Run Code Online (Sandbox Code Playgroud)
在QML方面,只是影响一个JS数组,QML引擎会自动将它转换为QVariant,使其易于理解为Qt:
KeyboardContainer.enableKeys = [12,48,26,49,10,3];
Run Code Online (Sandbox Code Playgroud)
就这样 !
| 归档时间: |
|
| 查看次数: |
5764 次 |
| 最近记录: |