簡體   English   中英

通過調用C ++函數設置加載程序組件

[英]Set loader component by calling C++ function

我只是想知道這樣的事情是否可能:

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

    sourceComponent: cppWrapper.getCurrentDisplay();
 }

在C ++中:

QDeclarativeComponent currentDisplay;

Q_INVOKABLE QDeclarativeComponent getCurrentDisplay() const
{ return currentDisplay; }

我在編譯它時遇到了麻煩(在moc文件編譯中失敗),但是如果可能的話,對我來說這可能是真正的捷徑

當然,您可以在C ++部分中創建Component(作為QQmlComponent)並將其返回到QML部分。 簡單示例(我使用Qt 5.4):

首先,我創建一個類以將其用作單例(只是為了易於使用)

COMMON.H

#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文件都在資源中,但這僅是示例,您可以將其放在所需的任何位置

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM