Reputation: 124
I am new to Qt and trying to create a custom property in Qt. For keeping it short i have merged the .h and .cpp file here but they are different in my main project. My main.cpp is
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "message.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
Message msg;
engine.rootContext()->setContextProperty("msg", &msg);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
qRegisterMetaType<MessageBody*>("MessageBody*");
return app.exec();
}
My message.h is
#include<messageBody.h>
class Message : public QObject
{
Q_OBJECT
Q_PROPERTY(MessageBody* body READ body WRITE setBody NOTIFY bodyChanged)
MessageBody ob;
public:
MessageBody* body()
{
return &ob;
}
void setBody(MessageBody* body)
{
ob.textUpdate(body->text());
emit bodyChanged();
}
signals:
void bodyChanged();
};
My messageBody.h is
class MessageBody : public QObject
{
Q_OBJECT
Q_PROPERTY(QString text READ text WRITE textUpdate NOTIFY textChanged)
QString ori_text;
public:
void textUpdate(const QString& new_txt)
{
if(new_txt != ori_text)
{
ori_text=new_txt;
emit textChanged();
}
}
QString text()
{
return ori_text;
}
signals:
void textChanged();
};
My main.qml is
import QtQuick 2.3
import QtQuick.Controls 1.2
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Text{
msg.body: "Hello, world!" //"Error here."
//I am expecting MessageBody::textUpdate()
//to get called i.e write method of Property
}
}
While executing, I am getting an error
qrc:/main.qml:18 Cannot assign to non-existent property "msg"
Thanks for the help.
Upvotes: 2
Views: 883
Reputation: 1751
I don't get 100% what you're tring to achieve, but maybe something like this:
main.qml
import QtQuick 2.3
import QtQuick.Controls 1.2
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Text{
text: msg.body.text
}
Component.onCompleted: {
msg.body.text = "Hello, world!"
}
}
main.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "message.h"
#include "MessageBody.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
qRegisterMetaType<MessageBody*>("MessageBody");
qRegisterMetaType<Message *>("Message");
Message msg;
engine.rootContext()->setContextProperty("msg", &msg);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
Does this work?
Upvotes: 2
Reputation: 655
This is because you are using your msg
object as if it was an existing property of the QML Text Element
and it is not that's why Qt give you this error.
I am not a QML pro developer but as I know you could or call your msg.body
with an existing signal of the Text Object such as onTextChange
o Component.onCompleted
or try to create a custom QML object
inheriting from Text
and that has a custom property msg.body
which make a link with your msg.body
of your c++ object.
Upvotes: 2