从QML调用C ++方法

时间:2014-06-19 12:22:12

标签: qt qml qtquick2

这里是Qt项目的最小骨架,以显示问题所在(运行该项目后检查控制台) http://uloz.to/xqxrXpdL/qtproject-zip

我尝试从qml调用公共插槽

Component.onCompleted: print(model.activate())

仍有错误:

TypeError: Property 'activate' of object QQmlDMObjectData(0x7fa35dd89eb0) is not a function

如果我试图从C ++动态调用该方法,它可以工作:

auto item = new TreeItem<MainMenuItem>(new MainMenuItem("kyklop"));

QMetaObject::invokeMethod(item, "activate");

如果我尝试从qml(例如级别)访问我的TreeItemTemplateBackend类的常规属性,它可以工作,所以只有在调用方法时才会出现问题。我认为它可能是该子类/模板类的东西。

注册qml:

qmlRegisterType<TreeItemTemplateBackend>("engine.ui", 1, 0, "TreeItemTemplateBackend");
qmlRegisterType<TreeItem<InspectorItem>>("engine.ui", 1, 0, "InspectorTreeItem");
qmlRegisterType<TreeItem<MainMenuItem>>("engine.ui", 1, 0, "MainMenuTreeItem");

TreeItem.h

#ifndef TREEITEM_H
#define TREEITEM_H

#include <QObject>
#include "TreeItemTemplateBackend.h"

template <typename T>
class TreeItem :  public TreeItemTemplateBackend
{

public:
    explicit TreeItem(QObject * parent = NULL);
    explicit TreeItem(T * data, QObject * parent = NULL);
    explicit TreeItem(TreeItem<T> & other);
    void addChild(TreeItem<T> * child);
    ~TreeItem() {}
};

#endif // TREEITEM_H

TreeItemTemplateBackend.h

#ifndef TREEITEMTEMPLATEBACKEND_H
#define TREEITEMTEMPLATEBACKEND_H

#include <QList>
#include <QQmlListProperty>

class TreeItemTemplateBackend : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QObject * data READ data WRITE setData NOTIFY dataChanged)
    Q_PROPERTY(QQmlListProperty<TreeItemTemplateBackend> childs READ childs NOTIFY childsChanged)
    Q_PROPERTY(int level READ level WRITE setLevel NOTIFY levelChanged)
public:
    explicit TreeItemTemplateBackend(QObject * parent = NULL);
    QObject * data() const;
    void setData(QObject * data);
    QQmlListProperty<TreeItemTemplateBackend> childs() const;
    void addChild(TreeItemTemplateBackend * child);
    int level() const;
    void setLevel(int level);
    void dump(QString propertyName) const;
    ~TreeItemTemplateBackend() {}
signals:
    void activated(); 
    void dataChanged();
    void childsChanged();
    void levelChanged();
public slots:
    void activate(); // this is what i am trying to call
protected:
    QObject * m_data;
    QList<TreeItemTemplateBackend *> m_children;
    int m_level;
    static void append_function(QQmlListProperty<TreeItemTemplateBackend> * property, TreeItemTemplateBackend * item);
    static TreeItemTemplateBackend * at_function(QQmlListProperty<TreeItemTemplateBackend> * property, int index);
    static void clear_function(QQmlListProperty<TreeItemTemplateBackend> * property);
    static int count_function(QQmlListProperty<TreeItemTemplateBackend> * property);
};

#endif // TREEITEMTEMPLATEBACKEND_H

2 个答案:

答案 0 :(得分:2)

QQmlDMObjectData是委托中使用的实际对象的包装器。原始对象可以通过属性modelData访问,因此model.modelData.activate()应该可以使用。

答案 1 :(得分:0)

如果你为它做准备&#34;方法&#34;并且您仍然将它用作方法,因此将其转换为方法:

...
public:
void Q_INVOKABLE activate();
...