Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Connect QML signal from delegate to C++ object



  • Hello,
    I have a QML ListView with a button into the delegate Item. I'd like to know if it's possible connect a delegate Item signal to a particular C++ object slot.



  • @fede hi,
    of course you can do that.
    Create your c++ class (subclass QObject) and the slot you need

    class MyClass: public QObject  
    { 
        Q_OBJECT 
    public: 
        explicit MyClass(QObject *parent = 0); 
      
    signals: 
      
    public slots: 
        void theSlot(){ ... }
    }; 
      
    

    Create an instance of the class in main.cpp and use setContextProperty() methode to make your object reachable in QML
    http://doc.qt.io/qt-5/qqmlcontext.html#setContextProperty

    #include "myclass.h"
      
    int main(int argc, char *argv[]) 
    { 
        QGuiApplication app(argc, argv); 
        MyClass c;  
        QQmlApplicationEngine engine; 
        engine.rootContext()->setContextProperty("myObj", &c);
        engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); 
      
        return app.exec(); 
    }
    

    then you can call theSlot()

    ..{
    onClicked: myObj.theSlot()
    }
    

Log in to reply