通过调用C ++函数设置加载程序组件

摩卡

我只是想知道是否有可能这样的事情:

Loader {
    id: loader
    objectName: "loader"
    anchors.centerIn: parent

    sourceComponent: cppWrapper.getCurrentDisplay();
 }

在C ++中:

QDeclarativeComponent currentDisplay;

Q_INVOKABLE QDeclarativeComponent getCurrentDisplay() const
{ return currentDisplay; }

我在编译它时遇到了麻烦(在moc文件编译中失败),但是如果可能的话,对我来说这可能是一个真正的捷径

Folibis

当然,您可以在C ++部分中创建Component(作为QQmlComponent)并将其返回到QML部分。简单示例(我使用Qt 5.4):

首先,我创建一个类以将其用作单例(只是为了易于使用)

普通

#include <QObject>
#include <QQmlComponent>

class Common : public QObject
{
    Q_OBJECT
public:
    explicit Common(QObject *parent = 0);
    ~Common();
    Q_INVOKABLE QQmlComponent *getComponent(QObject *parent);
};

common.cpp

QQmlComponent *Common::getComponent(QObject *parent) {
    QQmlEngine *engine = qmlEngine(parent);
    if(engine) {
        QQmlComponent *component = new QQmlComponent(engine, QUrl("qrc:/Test.qml"));
        return component;
    }
    return NULL;
}

现在,我创建并注册我的单身人士:

main.cpp

#include "common.h"

static QObject *qobject_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
    Q_UNUSED(engine)
    Q_UNUSED(scriptEngine)
    static Common *common = new Common();
    return common;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
        qmlRegisterSingletonType<Common>("Test", 1, 0, "Common", qobject_singletontype_provider);
        QQmlApplicationEngine engine;
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
        return app.exec();
}

好的,现在我们有了一个单例,并且在QML中使用它非常简单:

main.qml

import QtQuick 2.3
import Test 1.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    id: mainWindow

    Loader {
        id: loader
        objectName: "loader"
        anchors.centerIn: parent
        sourceComponent: Common.getComponent(mainWindow)
    }
}

也是我们用C ++创建的组件:

Test.qml

import QtQuick 2.3

Rectangle {
    width: 100
    height: 100
    color: "green"
    border.color: "yellow"
    border.width: 3
    radius: 10
}

请注意:我们所有的QML文件都在资源中,但这仅是示例,您可以将其放置在所需的任何位置

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章