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

Connecting Qt functionality with Qml



  • Hi ,

    Am writing play function to play music in Qt Cpp file but my UI is in Qml if i wanted to move that music slider according to my current playing song how can i link qt functionality with that slider image on my UI



  • So my first basic solution is this:
    in C++:

    // Update playtime information for UI
    // repeat this every tick
    engine->rootContext()->setContextProperty("playTime", secondsPlayed);
    
    // set songLength property when you change a song
    engine->rootContext()->setContextProperty("songLength", secondsSongLength);
    

    in QML you have then say a value property for your slider:

    Slider {
       value: playTime/songLength
    }
    

    QML binding will ensure that value will be recalculated each time the properties playTime/songLength are changed


  • Moderators

    @Sushma_MP
    instead of consecutively writing context properties i would suggest a cleaner way. (i am not quite sure if property binding is really working for context properties?)

    Create a custom (QObject derived) controller class and correctly define your properties. On each update notification just set the property.

    //cpp
    class MyController : public QObject
    {
           Q_OBJECT
           Q_PROPERTY( qreal progress READ progress WRITE setProgress NOTIFY progressChanged )
    
    ...
    
    signals:
         void progressChanged( qreal progress );
    
    protected:
           qreal progress() const { return mProgress; }
           void setProgress(qreal progress)
           {
                  if( mProgress != progress )
                  {
                      mProgress = progress;
                      emit progressChanged(progress);
                  }
           }
    
          qreal mProgress;
    };
    
    // register type to QML
    qmlRegisterType<MyController>();  //tell QML the available properties, methods, etc.; Also this type wont be createable within QML
    engine->rootContext()->setContextProperty( "MyControllerContextProperty", new MyController(engine) );
    
    //qml
    MyItem {
          id: root
    
          Connections {
                  target: MyControllerContextProperty
                  onProgress: root.doSomething()
          }
    
          // or also possible
          ProgressBar {
                 value: MyControllerContextProperty.progress   //gets automatically updated when you update the property in C++
          }
    }
    

    This technique works with every QObject derived class. Read on here.


Log in to reply