要让一个静态的类能够在 QML 中使用,可以通过以下步骤:

  1. 在 C++ 中定义一个静态类,并添加需要在 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;
};
  1. 在 main.cpp 中将该静态类作为一个上下文属性注册到 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();
}
  1. 在 QML 中通过上下文属性来访问该静态类的属性和方法。
import QtQuick 2.15

Item {
    width: 200
    height: 200

    Text {
        text: 'My Property: ' + MyStaticClass.myProperty
    }

    Button {
        text: 'Set Property'
        onClicked: {
            MyStaticClass.myProperty = 42
        }
    }
}

这样就可以在 QML 中使用静态的类了。在 QML 中可以直接访问该类的属性和方法,并且可以通过信号和槽机制与 C++ 代码进行交互。


原文地址: https://www.cveoy.top/t/topic/pI0W 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录