qtqmlqgadget

Q_GADGET Unknown method return type


I have a class MyWindow. This class call

MyWindow.h

class MyWindow : public QObject
{
   Q_OBJECT
   Q_PROPERTY(int nbMatch READ GetNbMatch NOTIFY matchChangedQMLL)

public:
   explicit MyWindow(QObject *parent = nullptr);
   explicit MyWindow(AsyncCalendarGetter& calendar, QObject *parent = nullptr);
   ~MyWindow();

   Q_INVOKABLE QString getFirstMatch() {
    return QString::fromUtf8(calendar->GetCalendar().front().GetDate().toString().c_str());
   }

   Q_INVOKABLE Date getFirstDate() {
    return calendar->GetCalendar().front().GetDate();
   }

   // ...
}

Date.h

#pragma once

#include <string>
#include <sstream>
#include <QObject>
#include <iostream>

class Date
{
   Q_GADGET
   Q_PROPERTY(std::string dateStr READ toString)
public:
   Date(std::string&& str);
   Date();
   Date(int day, int month, int year, int h, int m);

   friend std::ostream& operator<<(std::ostream& os, const Date& obj);

   Q_INVOKABLE std::string toString() const {
    std::stringstream ss;
    ss << *this;
    return ss.str();
   }

private:
  int day = 1;
  int month = 1;
  int year = 1970;
  int h = 0;
  int m = 0;
};

When I call the first function getFirstMatch in my QML, it works. But, the second function gtFirstDate does not work, I have an error message :

qrc:/main.qml:27: Error: Unknown method return type: Date

My QML

 Connections {
    target: mainmywindow
    onMatchChangedQMLL: {
        lbl0.text = "" + Number(mainmywindow.nbMatch) + " -> " + qsTr(mainmywindow.getFirstMatch()) // WORKS
        lbl1.text = "" + Number(mainmywindow.nbMatch) + " -> " + qsTr(mainmywindow.getFirstDate().toString()) // DOES NOT WORK
    }
 }

Someone have an idea ?

Thanks


Solution

  • You can find information about Q_DECLARE_METATYPE here:

    https://doc.qt.io/qt-5/qmetatype.html#Q_DECLARE_METATYPE

    According to it, you should do these steps to resolve your problem:

    1. Add Q_DECLARE_METATYPE(Date) after declaration of Date
    2. Add qRegisterMetaType<Date>(); somewhere before engine.load(url);

    (I assume you have QQmlApplicationEngine engine; in main() to load and run QML)

    Update: Also std::string not supported directly by QML, you should use QString