Solved Pass custom object in signal from QML
-
Hi,
I would like to send manually crafted object defined in c++ header file from onClick method in QML into legacy C++ code. I can make it working with basic types like QString, int, but is it possible with custom classes like MyMessage here:
class MyClass : public QObject { Q_OBJECT public slots: void addMessage(const MyMessage &msg) { qDebug() << "Called the C++ slot with message:" << msg.author(); } }; ... struct MyMessage : public QObject { Q_OBJECT MyMessage(QString author):author(author){} QString author; } ... engine.rootContext()->setContextProperty("MyClass",&myClass);
I need code like this to be working:
Button { text: "SendMessage" onClicked: { var message = MyMessage("Karel") // here i would like to set more attributes MyClass.addMessage(MyMessage(message)) } }
Thanks for any suggestion!
-
Hi@yeckel,
You can do it in following way- Register the class using
qmlRegisterType
qmlRegisterType<MyMessage>("MyMessage", 1, 0, "MyMessage")
- Import that type it in QML
import MyMessage 1.0
- Instantiate it
MyMessage { id: myMessage }
- Use it using its
id
myMessage.myMethod()
It would be better to add some properties defined using
Q_PROPERTY
inMyMessage
class so that they can be directly accessible from QML. Add accessor and mutator to it so as to access the data from other class.
So for eg. if you have a property like
Q_PROPERTY(QString quote READ quote WRITE setQuote NOTIFY quoteChanged)
From QML you can just do this:MyMessage { id: myMessage } myMessage.quote = "Some Quote"
Then you can send this object to
MyClass
using theid
MyClass.addMessage(myMessage)
More info here.
- Register the class using
-
Thanks! To instantiate that object that I was missing. One more point: the slot has to accept pointer not reference:
class MyClass : public QObject { Q_OBJECT public slots: void addMessage(MyMessage *msg) { qDebug() << "Called the C++ slot with message:" << msg->author(); } };
Without that i was getting an error: Error: Unknown method parameter type: MyMessage
-
@yeckel Right. Forgot to mention it here. You can mark the post as solved