问题描述
本显示如何从QML内调用C ++函数。
This page shows how to call C++ functions from within QML.
我想做的是通过C ++函数改变Button上的图像(触发状态改变或者完成)。
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).
我如何实现这一点?
UPDATE
由Radon,但是当我插入这行时立即:
I tried the approach by Radon, but immediately when I insert this line:
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 ++代码的连接。
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<QObject *>(viewer.rootObject());
}
}
推荐答案
你为图像设置一个 objectName
,你可以从C ++访问它很容易:
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"
}
}
在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";
}
// [...]
,
这篇关于C ++和QML之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!