C++ to QML signal issue



  • I am having issues accessing an intValueChanged signal. I apologize in advance for this newbie question.

    The class that defines the intValueChanged signal follows:

    class IntValue : public QObject
    {
        Q_OBJECT
        Q_PROPERTY(qint16 intValue READ intValue WRITE setIntValue NOTIFY intValueChanged)
    
    public:
        void setIntValue(const qint16 &a)
        {
            if (a != v)
            {
                v = a;
                emit intValueChanged();
            }
        }
    
        qint16 intValue() const
        {
            return v;
        }
    
    signals:
        void intValueChanged();
    
    private:
        qint16 v;
    };
    

    My main.cpp file contains the following:

    IntValue rotationAngle;
    engine.rootContext()->setContextProperty("rotationAngle", &rotationAngle);
    

    In my QML file, I can set read and set rotationAngle.intValue. For example, I can read rotationAngle.intValue as shown below:

    angle: rotationAngle.intValue;
    

    How would I access the intValueChanged signal?

    Thank you in advance.

    Hoyt


  • Moderators

    @Hoyt
    You can use Connections and keep the target as rotationAngle. Now since you have signal named intValueChanged Qt automatically provides a signal handler named onIntValueChanged. Use this handler in your Connections.
    More info:
    http://doc.qt.io/qt-5/qtqml-syntax-signals.html#receiving-signals-with-signal-handlers



  • Hi,

    I think you can use something like this:

    Component.onCompleted: {
        if(rotationAngle !== null && rotationAngle !== undefined) {
            rotationAngle.intValueChanged.connect(function (/* parameters from signal if needed */) {
                //Dome code here
            });
        }
    }
    

    Hope this help.



  • @p3c0

    Thank you very much. Connections, configured as you stated, worked perfectly.

    If I wanted to receive the same signal with a C++ object, would I also use Connections? If so, would you mind explaining how to configure Connections?

    Thanks again.

    Hoyt


  • Moderators

    @Hoyt You already have that signal in your IntValue class. So in case you are trying to access this signal from other C++ class you have the instantiated object here:

    IntValue rotationAngle;
    engine.rootContext()->setContextProperty("rotationAngle", &rotationAngle);
    

    Use this object and connect to its SIGNAL intValueChanged.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.