我正在尝试创建到我的自定义cpp类“EState”的连接。
EState包含三个类,其中两个子类具有一些自己的类。

到目前为止,我已经能够通过QML中的以下方式访问变量:

// ...
Estate.B.bSub.targetSpeed = 0
// ...

EState构造函数将初始化子类,而子类将初始化它的子类。

//main.cpp
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;

EState *state = new EState();


engine.rootContext()->setContextProperty("EState", state);

// main的结尾

//顶级类
class EState : public QObject
{
    Q_OBJECT
    Q_PROPERTY(EAState *A MEMBER mA NOTIFY aChanged)
    Q_PROPERTY(EBState *B MEMBER mB NOTIFY bChanged)
    Q_PROPERTY(QList<ECState*> Cs MEMBER mCs NOTIFY csChanged)

public:
    EState();
    ~EState(){}

    EAState * mA;
    EBState * mB;
    QList<ECState *> mCs;
    ECState *COne;
    ECState *CTwo;

signals:
    void aChanged();
    void bChanged();
    void csChanged();
};

EState::EState()
{
    mA = new EAState();
    mB = new EBState();
    COne = new ECState();
    CTwo = new ECState();

     mCs = {COne, CTwo};
}

//顶级类(class)结束

//中间类
class EBState : public QObject
{
    Q_OBJECT
    Q_PROPERTY(BSub * bSub MEMBER mBSub NOTIFY bSubChanged)

public:
    EBState();
    ~EBState(){}

    BSub *  mBSub;

signals:
    void bSubChanged();
};

EBState::EBState()
{
    mBSub = new BSub();
}

//结束中间类

//最内层
class BSub : public QObject {
    Q_OBJECT
    Q_PROPERTY(float targetSpeed MEMBER mTargetSpeed NOTIFY targetSpeedChanged)

public:
    BSub ()
    ~BSub (){}
    float mTargetSpeed = 0;

signals:
    void targetSpeedChanged();
};

MSub::MSub()
{
     mTargetSpeed = 0;
}

//最内层的结尾

在QML中,我想像以下方式(或类似方式)接收内部类的信号:
 Connections
 {
      target: EStates

      B.bSub.onTargetSpeedChanged:
      {
           console.log(targetSpeed);
      }
 }

当前错误消息是:
qrc:/ QML / main qml:204不存在的附加对象

最佳答案

您有2个错误:

  • QML中对象EState的名称中的错字,因为您将其注册为EState:setContextProperty("EState", state);,但将其用作target: EStates
  • Connections目标引用具有信号的对象,即EState.B.bSub而不是EState

  • 考虑到上述情况,解决方案是:
    Connections
    {
        target: EState.B.bSub
    
        onTargetSpeedChanged:
        {
            console.log(EState.B.bSub.targetSpeed);
            // or
            // console.log(target.targetSpeed);
        }
    }
    

    10-07 22:17