4

I have a STL codebase that need to be shared between a QtQuick 2.0 application (the graphical interface) and a purely STL application (the server). The interface can derive its classes from the shared STL codebase, so it can have Q_PROPERTYs, signals, slots, etc. but the shared data structures need to remain STL-only.

I'd like to avoid data duplication (std::string -> QString, etc.) so I tried to use std::string directly within the Q_PROPERTY system. Using Q_DECLARE_METATYPE(std::string) and qRegisterMetaType<std::string>(); and declaring properties like:

Q_PROPERTY(QString stldata READ stldata WRITE setSTLData NOTIFY stldataChanged)

makes my code compile, but QML still doesn't like std::strings.

Writing a text field with:

Text
{
 text: myserviceinterface.stldata
}

produces a warning saying Unable to assign std::string to QString, while appending an existing QML string:

Text
{
 text: "text: " + myserviceinterface.stldata
}

makes the Text control display a weird QVariant(std::string).

What am I doing wrong?

1 Answer 1

6

I am afraid you can't use std::string directly within QML, you have to convert to QString first.

In general, you can only export two kinds of C++ types to QML: QObject-derived classes and some build-in value types, see this documentation page. So using a QString as the type of a Q_PROPERTY only works because it has special built-in support in the QML engine. There is no way to add support for more of these value types like std::string (*).

Using qRegisterMetaType also doesn't help: It merely registers std::string as a meta type, which among others means it can be stored in a QVariant. It is (mostly) not relevant for QML integration.

So have your getter return a QString:

    Q_PROPERTY(QString stldata READ stldata WRITE setSTLData NOTIFY stldataChanged)
    QString stldata() const {
        return QString::fromStdString(myStlString);
    }

(*) Actually there is a way to add support for new value types, but that is private API in QML that needs to work directly with the underlying Javascript engine. The QtQuick module uses that private API to add support for e.g. the QMatrix4x4 value type.

Sign up to request clarification or add additional context in comments.

2 Comments

You're right, I gave up. Having a QString copy of an already available std::string is not the ideal solution however. This means more memory drained from an already constrained mobile device, more computation when updating both the strings and so on.
Sorry, you didn't mention another QString copy of the std::string as member variable, I just imagined it. Well, I suppose that I can just convert it every time that the interface needs to display the variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.