如何使用qmlRegisterType在QML中指定c ++类型?

时间:2019-05-13 13:16:21

标签: c++ qt qml

我需要在c ++中使用qmlRegisterType来定义QML的公共类型。那应该很简单,但是我在QML中有一个错误。 这是c ++。

QGuiApplication app(ai_argc, aipp_argv);

    qmlRegisterType<MiniModel>("miniModel", 1, 0, "MiniModel");//there it is !
    QQmlApplicationEngine engine;
    engine.addImportPath(QStringLiteral("..\\..\\..\\..\\Tools\\Qt\\5.12.0\\x64\\5.12.0\\msvc2017_64\\qml"));
    engine.load(QUrl(QStringLiteral("../../Inc/miniModel/miniModel.qml")));

    return app.exec();

这是QML

import QtQuick 2.5
import QtQuick.Window 2.5
import QtQuick.controls 2.5
import "..\\..\\x64\\Debug\\" miniModel 1.0 MiniModel//unknown component


ApplicationWindow {
    id: root
    width: 300
    height: 480
    visible: true
    property bool value: Minimodelqml.

    BackEnd {
        id: backend
    }

    TextField {
        text: backend.userName
        placeholderText: qsTr("User name")
        anchors.centerIn: parent

        onTextChanged: backend.userName = text
    }
}

我尝试过:

/*cpp*/qmlRegisterType<MiniModel>("miniModel", 1, 0, "MiniModel");
/*qml*/import miniModel 1.0 MiniModel //QML module not found
/*cpp*/qmlRegisterType<MiniModel>("anothertry.miniModel", 1, 0, "MiniModel");
/*cml*/import anothertry.miniModel 1.0//qml module not found

和其他一些人...我是QMl的新手,不知道如何处理它。

我没有使用QtCreator项目。这是Visual Studio 2017解决方案。也许问题出在那儿?

edit:使用单例的代码可以“很好”

2 个答案:

答案 0 :(得分:0)

import miniModel 1.0中的.qml应该可以工作

/*cpp*/qmlRegisterType<MiniModel>("miniModel", 1, 0, "MiniModel");
/*qml*/import miniModel 1.0 

答案 1 :(得分:0)

这些是我为将C ++类公开给QML引擎而遵循的一些常见步骤。

让我们先声明一些常量:

struct package_manager {
    static constexpr auto package_name = "com.mohabouje.package";
    static constexpr auto package_version_major = 0;
    static constexpr auto package_version_minor = 1;
}

然后创建您的Qt对象,并将属性公开给QML engine

class MyObject : public QObject {
    Q_OBJECT
    Q_PROPERTY(double awesome READ awesome WRITE setAwesome NOTIFY awesomeChanged)
public:
    // ...
    double awesome();
    void setAwesome(double);
signals:
    void awesomeChanged(double);
};

在您的主机上,然后执行以下操作:

int main(int argc, char* argv[]) {
    QApplication app(argc, argv);

    qmlRegisterType<MyObject>(package_manager::package_name,
        package_manager::package_version_major,
        package_manager::package_version_minor, "MyObject");

    QQmlApplicationEngine engine;
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;
    return app.exec();
}

您的main.qml变为:

import com.mohabouje.pacakge 0.1

ApplicationWindow {
    id: root
    width: 300
    height: 480
    visible: true

    Component.onCompleted: {
        MyObject {
            awesome: 25
        }
    }

}

有关更多详细信息,请参见此tutorial