0

在我的项目中,我使用 C++,QScxmlCppDataModel,当我启动状态机时,总是出现错误,“没有数据模型实例化”,

我按照 Qt 文档说

1、在scxml文件中添加数据模型

<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" binding="early" xmlns:qt="http://www.qt.io/2015/02/scxml-ext" datamodel="cplusplus:DataModel:DataModel.h" name="PowerStateMachine" qt:editorversion="4.6.1" initial="nomal">

2、新建数据模型子类

#include "qscxmlcppdatamodel.h"
#include <QScxmlEvent>

class DataModel :public QScxmlCppDataModel
{
    Q_OBJECT
    Q_SCXML_DATAMODEL

public:
//    DataModel();

    bool isMoreThan50() const;
    bool isLessThan50() const ;

    int m_power;
    QString m_Descript;
    QVariant m_var;


};

3、加载和启动状态机

    m_stateMachine = QScxmlStateMachine::fromFile(":/powerStateMachine.scxml");
    for(QScxmlError& error:m_stateMachine->parseErrors())
    {
        qDebug()<<error.description();
    }
    m_stateMachine->connectToEvent("powerLoss", this, &MainWindow::onPowerLossEvent);
    m_stateMachine->connectToEvent("pwoerUp", this, &MainWindow::onPowerUpEvent);

    m_stateMachine->connectToState("low", this, &MainWindow::onLowState);
    m_stateMachine->connectToState("nomal", this, &MainWindow::onNomalState);
    m_stateMachine->connectToState("danger", this, &MainWindow::onDangerState);
    m_stateMachine->connectToState("full", this, &MainWindow::onFullState);
    DataModel *dataModel = new DataModel;
    m_stateMachine->setDataModel(dataModel);
    m_stateMachine->init();

    m_stateMachine->start();

错误图像

但仍然有一个错误:“没有数据模型实例化”,当我启动状态机时,有人知道如何修复它吗?谢谢你

4

1 回答 1

0

Qt 的文档QScxmlCppDataModel专门说:

在运行时加载 SCXML 文件时,不能使用 SCXML 的 C++ 数据模型。

这正是您正在做的事情,所以不要在运行时加载 scxml 文件:

m_stateMachine = QScxmlStateMachine::fromFile(":/powerStateMachine.scxml");

直接使用编译好的状态机:

MyStateMachine statemachine;
MyDataModel datamodel;
statemachine.setDataModel(&datamodel);

在上面的例子中:

1- MyStateMachine是您分配给<name>scxml 元素(即scxml 文件/模型)的属性的值。

2-MyDataModel是您为 c++ 数据模型类指定的名称(即您的类派生自QScxmlCppDataModel

class MyDataModel : public QScxmlCppDataModel
{
    Q_OBJECT
    Q_SCXML_DATAMODEL
public:
    MyDataModel();
};

答案为时已晚,但希望对其他人有所帮助。

于 2021-07-23T18:45:03.897 回答