Link slot in C++ to signal in QML



  • Hello,

    I'm learning Qt/QML and I'm in troubles about linking a slot C++ to a signal QML. I can't find the way to work with this.

    Here is my code

    main.cpp
    
            QQmlApplicationEngine engine;
            engine.rootContext()->setContextProperty("personne",p);
            engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    
            QQuickView view(QUrl(QStringLiteral("qrc:/main.qml")));
            QObject *o = view.rootObject();
            
            QObject::connect(o,SIGNAL(),p,SLOT(changedAgain());
    
    personne.h
    
    class Personne : public QObject
    {
        Q_OBJECT
        Q_PROPERTY(QString firstName READ firstName WRITE setFirstName NOTIFY firstNameChanged)
        Q_PROPERTY(QString lastName READ lastName WRITE setLastName NOTIFY lastNameChanged)
    
    public:
        Q_INVOKABLE bool postMessage(const QString &msg);
    
        explicit Personne(QObject *parent = 0);
    
        QString lastName() const;
        void setLastName(const QString &lastName);
    
        QString firstName() const;
        void setFirstName(const QString &firstName);
    
    signals:
        void firstNameChanged();
        void lastNameChanged();
    
    public slots:
        void changedAgain();
    
    private:
        QString m_firstName;
        QString m_lastName;
    };
    
    main.qml
    
    import QtQuick 2.4
    import QtQuick.Window 2.2
    import QtQuick.Controls 1.1
    import cpp.models.person 1.0
    
    Window {
        visible: true
    
        signal upperTextSignal(string text)
    
        MouseArea {
            anchors.fill: parent
            onClicked: {
                Qt.quit()
            }
        }
    
        Personne {
            id: person
            firstName: "John"
            lastName: "Doe"
            onFirstNameChanged: {
                console.log("First name changed. From C++ : " + personne.firstName)
                upperTextSignal(person.firstName)
            }
    
            onLastNameChanged: {
                console.log("Last name changed.From C++ : "+ personne.firstName)
            }
        }
    }
    

    For me, its seems good but I can't access to my signal, which is declared in main.qml, from the main.cpp.

    I will appreciate the explination of my mystake.


  • Moderators

    @Lordful said:

    QObject::connect(o,SIGNAL(),p,SLOT(changedAgain());

    Specify the signal: SIGNAL(upperTextSignal(QString))

    See also http://doc.qt.io/qt-5/signalsandslots-syntaxes.html#connecting-c-objects-to-qml-objects

    EDIT: Why do you load main.qml 2 times? (Once using QQmlApplicationEngine and once using QQuickView)


Log in to reply
 

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