如何告诉QML绑定有关其他依赖关系? [英] How to tell a qml binding about additional dependencies?

查看:54
本文介绍了如何告诉QML绑定有关其他依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++实现的快速项目,它提供了多个属性和带有返回值的Q_INVOKABLE方法.这些方法大多数都取决于这些属性.

I have a C++ implemented Quick Item and it offeres multiple properties and Q_INVOKABLE methods with return values. Most of these methods depend on these properties.

我可以为方法定义一个通知信号吗?或者在绑定到它时,是否可以添加其他依赖项,以便再次评估该方法?

Can I define a notify signal for methods? Or when binding to it, can I add additional dependencies so the method is evaluated again?

在此示例中,我希望只要 theItem.something 更改,所有文本项都会更新.

In this example I want all text items to be updated whenever theItem.something changes.

SimpleCppItem {
    id: theItem
    something: theSpinBox.value
}

RowLayout {
    SpinBox { id: theSpinBox; }

    Repeater {
        model: 10
        Text { text: theItem.computeWithSomething(index) }
    }
}

SimpleCppItem 的实现如下所示:

class SimpleCppItem : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(int something READ something WRITE setSomething NOTIFY somethingChanged)

public:
    explicit SimpleCppItem(QQuickItem *parent = Q_NULLPTR) :
        QQuickItem(parent),
        m_something(0)
    { }

    Q_INVOKABLE int computeWithSomething(int param)
    { return m_something + param; } //The result depends on something and param

    int something() const { return m_something; }
    void setSomething(int something)
    {
        if(m_something != something)
            Q_EMIT somethingChanged(m_something = something);
    }

Q_SIGNALS:
    void somethingChanged(int something);

private:
    int m_something;
};

推荐答案

这对于函数是不可能的.但是有一些工作技巧:

That is not possible with functions. But there are some workarouds:

"Small Hack"(您会收到警告M30:警告,请勿使用逗号表达式)感谢GrecKo,再也没有警告了!

"Small Hack" (You get warning M30: Warning, Do not use comma expressions Thanks to GrecKo, no warning anymore!

Repeater {
        model: 10
        Text {
            text: {theItem.something; return theItem.computeWithSomething(index);}
        }
    }

或者您将中继器中的每一项都与"somethingChanged"信号相连:

Or you connect every item in the repeater with the "somethingChanged" signal:

Repeater {
    model: 10
    Text {
        id: textBox
        text: theItem.computeWithSomething(index)
        Component.onCompleted: {
            theItem.somethingChanged.connect(updateText)
        }
        function updateText() {
            text = theItem.computeWithSomething(index)
        }
    }
}

=====原始问题=====

===== ORIGNAL QUESTION =====

您可以像这样在QML文件中捕获信号:

You can catch the signal in the QML file like this:

SimpleCppItem {
    id: theItem
    something: theSpinBox.value

    onSomethingChanged() {
       consoloe.log("Catched: ",something)
       //something ist the name of the parameter
    }
}

这篇关于如何告诉QML绑定有关其他依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆