Nominate our 2022 Qt Champions!

Expose a C++ typedef to QML

  • How can I make QML engine to recognize C++ typedef? I tried to define my type both by using and typedef:
    Header file:

    using primary_key = qint64;
    // or typedef qint64 primary_key;

    Source file:

    void init_db()

    But when I call a Q_INVOKABLE function which returns primary_key, I get "Unknown method return type" error at runtime.

  • This post is deleted!

  • First of all a line from the docs:

    To use the type T in queued signal and slot connections, qRegisterMetaType<T>() must be called before the first connection is established.

    Maybe you could try to move qRegisterMetaType<primary_key>(); into the constructor of the class.

  • @ttuna Thanks, but I'm not using the type in signal and slot connections.

  • @m_andrej said:

    @ttuna Thanks, but I'm not using the type in signal and slot connections.

    Not having signals emitted by your own does not mean that Qt doesn't in the background.
    If QmlEngine and your QObject are living in different threads i think they'll communicate over signal / slot.
    I ran into a similar problems and because the situation in your code example isn't clear i thought it's worth a shot.

  • @ttuna OK, I see. But I'm calling qRegisterMetaType<primary_key>(); before QmlEngine is even created. Sorry for not mentioning this at the first time.

  • Maybe you can post a more detailed code example because it's difficult to take all possible scenarios into account (e.g. different namespaces, ...)

  • Here is the complete example:

    TestClass.h (doesn't have a cpp file):

    #pragma once
    #include <QObject>
    using primary_key = qint64;
    class TestClass : public QObject
        explicit TestClass(QObject *parent = 0) : QObject(parent) {}
        Q_INVOKABLE primary_key lastInsertRowid() { return 0; }


    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QtQml>
    #include "TestClass.h"
    int main(int argc, char *argv[])
        QGuiApplication app(argc, argv);
        qmlRegisterType<TestClass>("pokus", 1, 0, "TestClass");
        QQmlApplicationEngine engine;
        return app.exec();


    import QtQuick 2.4
    import QtQuick.Controls 1.1
    import QtQuick.Window 2.2
    import pokus 1.0
    Window {
        visible: true
        Button {
            anchors.centerIn: parent
            text: "Klikni"
        TestClass {
            id: testObj

    When I run the program and click the button, I get qrc:/main.qml:14: Error: Unknown method return type: primary_key.

Log in to reply