Custom type in c++ signal with qt5



  • Hello,

    I wan't to deliver a custom type in a signal from c++ to qml.

    The signal is delivered and the connected javascript function is called. But there is no access to the properties in the custom type.

    Is it possible to use custom types in c++/qml-signals? Do I have to register the custom type somewhere?

    I used the following coding. The logoutput is:

    finished true QVariant(CustomType)
    toString
    valueOf

    C++:

    @class Adapter : public QObject
    {
    Q_OBJECT
    public:
    explicit Adapter(QObject *parent = 0);
    Q_INVOKABLE void start()
    {
    CustomType c;
    c.setNr(1);
    c.setName("Paula");
    finished(true, QVariant::fromValue(c));
    }

    signals:
    void finished(bool ok, QVariant v);
    public slots:

    };@

    @class CustomType : public QObject
    {
    Q_OBJECT
    Q_PROPERTY (QString name READ name WRITE setName)
    Q_PROPERTY (int nr READ nr WRITE setNr)
    public:
    CustomType(QObject *parent = 0) : QObject(parent)
    {
    m_nr = 0;
    m_name = "";
    }

    CustomType(const CustomType& c) : QObject()
    {
        this->m_name = c.name();
        this->m_nr = c.nr();
    }
    
    void setNr(int v)
    {
        m_nr = v;
    }
    void setName(QString name)
    {
        m_name = name;
    }
    int nr() const
    {
        return m_nr;
    }
    QString name() const
    {
        return m_name;
    }
    

    private:
    int m_nr;
    QString m_name;
    };@

    @int main(int argc, char *argv[])
    {
    QGuiApplication app(argc, argv);

    Adapter a;
    
    QtQuick2ApplicationViewer viewer;
    
    viewer.rootContext()->setContextProperty("adapter", &a);
    
    viewer.setMainQmlFile(QStringLiteral("qml/meta/main.qml"));
    viewer.showExpanded();
    
    return app.exec();
    

    }@

    QML:

    @Rectangle {
    MouseArea {
    anchors.fill: parent
    onClicked: {
    adapter.start();
    }
    }

    Component.onCompleted: {
        adapter.onFinished.connect(finished);
    }
    
    function finished(ok, v)
    {
        console.debug("finished " + ok + " " + v);
        for (var t in v)
        {
            console.log(t);
        }
    }
    

    }
    @



  • For QObject-derived types, see https://bugreports.qt-project.org/browse/QTBUG-28619 for a solution to your problem.

    Cheers,
    Chris.


Log in to reply
 

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