两个qml之间通信_C ++和QML之间的通信

This page shows how to call C++ functions from within QML.

What I want to do is change the image on a Button via a C++ function (trigger a state-change or however it is done).

How can I achieve this?

UPDATE

I tried the approach by Radon, but immediately when I insert this line:

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

Compiler complains like this:

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)

In case it is relevant, QMLCppBinder is a class that I try to build to encapsulate the connections from several QML pages to C++ code. Which seems to be trickier than one might expect.

Here is a skeleton class to give some context for this:

class QMLCppBinder : public QObject

{

Q_OBJECT

public:

QDeclarativeView viewer;

QMLCppBinder() {

viewer.setSource(QUrl("qml/Connect/main.qml"));

viewer.showFullScreen();

// ERROR

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

}

}

解决方案

If you set an objectName for the image, you can access it from C++ quite easy:

main.qml

import QtQuick 1.0

Rectangle {

height: 100; width: 100

Image {

objectName: "theImage"

}

}

in C++:

// [...]

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

view.show();

// get root object

QObject *rootObject = dynamic_cast(view.rootObject());

// find element by name

QObject *image = rootObject->findChild(QString("theImage"));

if (image) { // element found

image->setProperty("source", QString("path/to/image"));

} else {

qDebug() << "'theImage' not found";

}

// [...]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值