11

このページでは、QML 内から C++ 関数を呼び出す方法を示します。

私がやりたいのは、C++関数を介してボタンの画像を変更することです(状態変更をトリガーするか、それが行われます)。

どうすればこれを達成できますか?

アップデート

ラドンによるアプローチを試みましたが、すぐに次の行を挿入すると:

    QObject *test = dynamic_cast<QObject *>(viewer.rootObject());

コンパイラは次のように文句を言います:

    error: cannot dynamic_cast '((QMLCppBinder*)this)->QMLCppBinder::viewer.QDeclarativeView::rootObject()' (of type 'struct QGraphicsObject*') to type 'class QObject*' (source is a pointer to incomplete type)

関連する場合、QMLCppBinder は、いくつかの QML ページから C++ コードへの接続をカプセル化するために構築しようとするクラスです。これは、予想以上に難しいようです。

これに何らかのコンテキストを与えるためのスケルトン クラスを次に示します。

    class QMLCppBinder : public QObject
    {
        Q_OBJECT
    public:
        QDeclarativeView viewer;

        QMLCppBinder() {
            viewer.setSource(QUrl("qml/Connect/main.qml"));
            viewer.showFullScreen();
            // ERROR
            QObject *test = dynamic_cast<QObject *>(viewer.rootObject());
        }
    }
4

2 に答える 2

15

画像にを設定するobjectNameと、C++ から非常に簡単にアクセスできます。

main.qml

import QtQuick 1.0

Rectangle {
    height: 100; width: 100

    Image {
        objectName: "theImage"
    }
}

C++ で:

// [...]

QDeclarativeView view(QUrl("main.qml"));
view.show();

// get root object
QObject *rootObject = dynamic_cast<QObject *>(view.rootObject());

// find element by name
QObject *image = rootObject->findChild<QObject *>(QString("theImage"));

if (image) { // element found
    image->setProperty("source", QString("path/to/image"));
} else {
    qDebug() << "'theImage' not found";
}

// [...]

QObject.findChild()QObject.setProperty()

于 2011-04-19T10:28:57.860 に答える
5

したがって、次のように、C++ オブジェクトを C++ の QDeclarativeView のコンテキスト プロパティとして設定できます。

QDeclarativeView canvas;
ImageChanger i; // this is the class containing the function which should change the image
canvas.rootContext()->setContextProperty("imgChanger", &i);

ImageChangerクラスで、次のようなシグナルを宣言します。

void updateImage(QVariant imgSrc);

次に、画像を変更したい場合は、 を呼び出しますemit updateImage(imgSrc);

QML で、次のようにこのシグナルをリッスンします。

Image {
    id: imgToUpdate;
}

Connections {
    target: imgChanger;
    onUpdateImage: {
        imgToUpdate.source = imgSrc;
    }
}

お役に立てれば。

于 2011-04-19T07:12:58.277 に答える