static的类如何被qml使用
要让一个static的类能够在QML中使用,可以通过以下步骤:
- 在C++中定义一个static类,并添加需要在QML中使用的属性和方法。
 
class MyStaticClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int myProperty READ myProperty WRITE setMyProperty NOTIFY myPropertyChanged)
public:
    static MyStaticClass* instance()
    {
        static MyStaticClass* s_instance = new MyStaticClass();
        return s_instance;
    }
    int myProperty() const
    {
        return m_myProperty;
    }
    void setMyProperty(int value)
    {
        if (m_myProperty == value)
            return;
        m_myProperty = value;
        emit myPropertyChanged();
    }
signals:
    void myPropertyChanged();
private:
    explicit MyStaticClass(QObject *parent = nullptr)
        : QObject(parent), m_myProperty(0)
    {}
    int m_myProperty;
};
- 在main.cpp中将该static类作为一个上下文属性注册到QML引擎中。
 
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("MyStaticClass", MyStaticClass::instance());
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}
- 在QML中通过上下文属性来访问该static类的属性和方法。
 
import QtQuick 2.15
Item {
    width: 200
    height: 200
    Text {
        text: "My Property: " + MyStaticClass.myProperty
    }
    Button {
        text: "Set Property"
        onClicked: {
            MyStaticClass.myProperty = 42
        }
    }
}
这样就可以在QML中使用static的类了。在QML中可以直接访问该类的属性和方法,并且可以通过信号和槽机制与C++代码进行交互
原文地址: https://www.cveoy.top/t/topic/hZWG 著作权归作者所有。请勿转载和采集!