Assign C++ object to Text element (implicit conversion to QString)
-
wrote on 29 Aug 2013, 15:21 last edited by
Hello,
I'm trying to implicitly convert an object to QString in order to
assign it to a Text element in qml.I think an example makes things clear:
@class Bar : public QObject
{
...
Q_INVOKABLE QString value(int param = -1);
};class Foo : public QObject
{
...
Q_PROPERTY(Bar * bar READ bar WRITE setbar NOTIFY onBarChanged);
};@A Foo object is registered as context property at application start:
@viewer.rootContext()->setContextProperty("Foo", &fooObject);@In qml the following works perfectly:
@Text
{
...
text: Foo.bar.value()
}@But in most cases I do not need to give a parameter to the value call() and it would
be much more straight forward if I could just write
@Text
{
...
text: Foo.bar
}@At the moment there's a runtime error which says "Unable to assign Bar to QString".
I tried to add a type cast operator to Bar:
@ Q_INVOKABLE operator QString()
{return value();}@But this did not resolve the problem.
Is it possible to convert an object to a QString implicitly? And if yes: how?
Thank you very much in advance,
Martin -
Hi,
I'm not 100% sure, but try implementing operator=() to assign a Bar to a QString
-
wrote on 30 Aug 2013, 07:06 last edited by
Hi JKSH,
thank's for your response.
I think overloading the assignment operator does not work unless I implement this operator in QString class directly (Bar should be assigned to QString not QString to Bar).Also overloading the "operator=" globally does not work. While this works well for other operators like << operator= seems to be a special case because the compiler tells me that "operator=" had to be a static member:
@QString & operator=(QString & str, const CTextProxy & rhs)
{
str = rhs.value();
return str;
}@Best regards,
Martin -
Then it can't be done, I'm afraid.
I actually just remembered: It doesn't make sense to convert a QObject to a string, either implicitly or explicitly. The reasoning is given "here":http://qt-project.org/doc/qt-5.1/qtcore/object.html#identity-vs-value -- QObjects should be treated as identities, not values. Otherwise, Qt's object model breaks down.
Instead, you should extract a string property from the QObject and copy that string, which is what text: Foo.bar.value() should do.
-
wrote on 13 Sept 2013, 09:57 last edited by
Hi JKSH,
thank you very much.