Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call arbitrary C++ functions from QML right at the object's creation?

Tags:

c++

qt

qml

Here's my main.qml:

import QtQuick 2.0
import A 1.0

Item {

    width: 1280
    height: 720

    OpenGlVideoQtQuick {

    }
}

Here's a part of OpenGlVideoQtQuick:

class OpenGlVideoQtQuick : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(qreal t READ t WRITE setT NOTIFY tChanged)

public:
    OpenGlVideoQtQuick();

    qreal t() const { return m_t; }
    void setT(qreal t);
    Q_INVOKABLE void initRtspMedia(const QString &uri);
}

How do I call initRtspMedia() from QML right at the creation of the OpenGlVideoQtQuick QML object? I've only seen how can buttons and other things call C++ code, but not how to call it immediately.

like image 771
Guerlando OCs Avatar asked Dec 02 '25 05:12

Guerlando OCs


1 Answers

For this case you can use Component.onCompleted:

import QtQuick 2.0
import A 1.0

Item {

    width: 1280
    height: 720

    OpenGlVideoQtQuick {
        id: opengl_video
        Component.onCompleted: opengl_video.initRtspMedia("some uri")
    }
}

Or from C++ you can do it with the help of QQmlParserStatus:

class OpenGlVideoQtQuick : public QQuickItem, public QQmlParserStatus
{
    Q_OBJECT
    Q_PROPERTY(qreal t READ t WRITE setT NOTIFY tChanged)
    Q_INTERFACES(QQmlParserStatus)
public:
    OpenGlVideoQtQuick();

    qreal t() const { return m_t; }
    void setT(qreal t);
    Q_INVOKABLE void initRtspMedia(const QString &uri);

   void classBegin() {}
   void componentComplete() {
       initRtspMedia("some uri");
   }
}
like image 51
eyllanesc Avatar answered Dec 03 '25 21:12

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!