如何告诉qml绑定其他依赖项?

时间:2017-07-05 08:59:55

标签: c++ data-binding qml qt5 qtquick2

我有一个C ++实现的Quick Item,它提供了多个属性和带有返回值的Q_INVOKABLE方法。大多数这些方法都依赖于这些属性。

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

在此示例中,我希望在theItem.something更改时更新所有文本项。

Screenshot of my example application

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;
};

1 个答案:

答案 0 :(得分:1)

功能无法实现。但是有一些工作方法:

“小黑客”(你收到警告M30:警告,不要使用逗号表达式感谢GrecKo,不再有任何警告!

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

或者您使用“somethingChanged”信号连接转发器中的每个项目:

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文件中捕获信号:

SimpleCppItem {
    id: theItem
    something: theSpinBox.value

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