Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Assign C++ object to Text element (implicit conversion to QString)
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:
In qml the following works perfectly:
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
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()
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,
I'm not 100% sure, but try implementing operator=() to assign a Bar to a QString
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();
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.
thank you very much.