Search code examples
qtqmlqtquick2property-binding

How to bind a property to a singleton object property from QML


There is a question about how to bind from a singleton object property to a QML property. But what about if we like to bind a QML property to a singleton object.

Here is the singleton class definition,

class Singleton : public QObject {
    Q_OBJECT
    Q_PROPERTY(QString name READ name WRITE setName)
public:
    explicit Singleton(QObject *parent = nullptr);
    QString name() const;
    void setName(const QString &name);
private:
    QString m_name;
};

And on QML

property string qmlName: textField.text
TextField {
    id: textField
}

I would like to bind textField.text to Singleton object name property. It is possible to bind it with a workaround like,

onQmlNameChanged: {
    Singleton.name = qmlName;
}

But that won't be an Property Binding actually, because it is an assignment.

So is there a more nature binding way to a singleton object property?


Solution

  • You could try to assign the binding like this:

    Component.onCompleted: Singleton.name = Qt.binding(function() { return qmlName })
    

    It works for normal QML-Objects, not sure it works with a singleton class, though. Anyhow, you can read more about this approach in the section "Creating Property Bindings from JavaScript".