简体   繁体   中英

Declare global strings for use in qml and cpp files

I have about 200 string constants that I want to declare in some .h file and access globally in my qml and .cpp files in my Qt project. I have been able to do that with enums by using Q_NAMESPACE and Q_ENUM_NS(enumName). How can I do a similar thing with strings?

Thanks

I don't know how to do with global, but you can maybe do like that :

https://doc.qt.io/qt-5/qtqml-cppintegration-definetypes.html#registering-c-types-with-the-qml-type-system

For example with one string named myStr :

class backend_class : public QObject
{
    Q_OBJECT

    Q_PROPERTY(QString myStr READ myStr WRITE myStr NOTIFY myStrChanged ) 

    public: 
        QString myStr() const { return a_myStr ; } 

        void myStr(QString value) { 
            if (a_myStr == value) return; 
            a_myStr = value; 
            emit myStrChanged(value); 
        } 

        Q_SIGNAL void myStrChanged(QString value);

    private: 
        QString a_myStr;
};

In the main.cpp add this before the engine load :

qmlRegisterType<backend_class>(
    "my.cpp.qml.backend", 1, 0, "BackEnd"
    );

And in your main.qml add a component :

BackEnd { id: cpp }

Now your string is availlable in your QML code like that :

cpp.myStr

You can do the same with a list :

// funny macro property automation
#define AUTO_PROPERTY(TYPE, NAME) \
    Q_PROPERTY(TYPE NAME READ NAME WRITE NAME NOTIFY NAME ## Changed ) \
    public: \
       TYPE NAME() const { return a_ ## NAME ; } \
       void NAME(TYPE value) { \
          if (a_ ## NAME == value) return; \
          a_ ## NAME = value; \
          emit NAME ## Changed(value); \
        } \
       Q_SIGNAL void NAME ## Changed(TYPE value);\
    private: \
       TYPE a_ ## NAME;

class backend_class : public QObject
{
    Q_OBJECT
    AUTO_PROPERTY( QStringList, strings )

public:
    backend_class() {

        a_strings << QString("Hello");
        a_strings << QString("Hello");
        a_strings << QString("Hello");

    }
};

Note that the QStringList will be casted as an array in QML.

For a more complicated type use this :

https://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html#properties-with-object-list-types https://code.qt.io/cgit/qt/qtdeclarative.git/tree/examples/qml/referenceexamples/properties?h=5.14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM