SCXML 媒体播放器
向 C++ 数据模型发送数据并从中接收数据。
Media Player演示如何从 C++ 数据模型访问数据。通过该数据模型,可为expr属性和<script>
元素编写 C++ 代码。数据模型的数据部分由QScxmlCppDataModel 的子类支持,Qt SCXML 编译器 (qscxmlc
) 为其生成调度方法。
用户界面使用Qt Quick 创建。
运行示例
运行示例 Qt Creator,打开Welcome 模式,然后从Examples 中选择示例。更多信息,请参见Qt Creator: 教程:构建并运行。
使用 C++ 数据模型
我们将数据模型指定为 SCXML 文件中<scxml>
元素的datamodel属性值:
<scxml
xmlns="http://www.w3.org/2005/07/scxml"
version="1.0"
name="MediaPlayerStateMachine"
initial="stopped"
datamodel="cplusplus:TheDataModel:thedatamodel.h"
数据模型属性的格式为:cplusplus:<class-name>:<classdef-header>
。因此,我们需要一个名为thedatamodel.h的文件,其中包含QScxmlCppDataModel 的子类:
#include "qscxmlcppdatamodel.h" #include <QtQml/qqml.h> class TheDataModel: public QScxmlCppDataModel { Q_OBJECT Q_SCXML_DATAMODEL
QScxmlCppDataModel 派生自 ,因此我们在定义的私有部分添加 宏,就在开头括号之后。然后,我们将 宏放在 之后。该宏扩展为虚拟方法的声明,其实现由 编译器生成。QObject Q_OBJECT
Q_SCXML_DATAMODEL
Q_OBJECT
Qt SCXML
在 SCXML 文件中,我们在<script>
元素中指定 C++ 语句,并使用expr属性访问数据模型:
<state id="stopped"> <transition event="tap" cond="isValidMedia()" target="playing"/> </state> <state id="playing"> <onentry> <script> media = eventData().value(QStringLiteral("media")).toString(); </script> <send event="playbackStarted"> <param name="media" expr="media"/> </send> </onentry> <onexit> <send event="playbackStopped"> <param name="media" expr="media"/> </send> </onexit> <transition event="tap" cond="!isValidMedia() || media == eventData().value(QStringLiteral("media"))" target="stopped"/> <transition event="tap" cond="isValidMedia() && media != eventData().value(QStringLiteral("media"))" target="playing"/> </state>
Qt SCXML 编译器会生成各种evaluateTo
方法,并将表达式和脚本转换为mediaplayer.cpp 中这些方法内部的 lambdas:
bool TheDataModel::evaluateToBool(QScxmlExecutableContent::EvaluatorId id, bool *ok) { .... return [this]()->bool{ return isValidMedia(); }(); .... } QVariant TheDataModel::evaluateToVariant(QScxmlExecutableContent::EvaluatorId id, bool *ok) { .... return [this]()->QVariant{ return media; }(); .... } void TheDataModel::evaluateToVoid(QScxmlExecutableContent::EvaluatorId id, bool *ok) { .... [this]()->void{ media = eventData().value(QStringLiteral("media")).toString(); }(); .... }
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.