Search code examples
c++qtqmlqmediaplayer

How can I integrate QML MediaPLayer with C++ side


I have developed a QML based video player program using MediaPlayer element. The program has most of basic functionality of a video player(play,pause,vol up/down,forward,bakcward etc.). My next task is add subtitle to a video and I need to use metaObject method of MediaPlayer element but QML side does allow that funtionality, it says:

Note: This property is not accessible from QML.

There is a description in the document related metaObject which is confusing my mind:

mediaObject : variant
This property holds the native media object.

It can be used to get a pointer to a QMediaPlayer object in order to integrate with C++ code.

QObject *qmlMediaPlayer; // The QML MediaPlayer object
QMediaPlayer *player = qvariant_cast<QMediaPlayer *>(qmlMediaPlayer->property("mediaObject"));

What is this supposed to mean? How can I integrate QML MediaPlayer with C++? Any help would be great, thanks.


Solution

  • This will depend on how exactly you launch the QML application. Suppose it is set up like this:

    int main(int argc, char **argv)
    {
       // Q(Gui)Application setup...
        
       QQmlApplicationEngine engine;
       engine.load(QUrl("qrc:/main.qml"));
    
       // ...
    }
    

    And somewhere inside the QML object hierarchy you have a MediaPlayer:

    MediaPlayer {
        objectName: "player"
        // ...
    }
    

    It's important to set the objectName property, so that you can look up the MediaPlayer instance by this name in the C++ code. After loading the QML document as above, the engine has a single root object you can search with findChild or findChildren (adapted from this answer):

    auto qmlPlayer = engine.rootObjects()[0]->findChild<QObject*>("player");
    auto player = qvariant_cast<QMediaPlayer*>(qmlPlayer->property("mediaObject"));
    // use the QMediaPlayer*