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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top