此page显示了如何从QML内调用C++函数。
我要做的是通过C++函数更改按钮上的图像(触发状态更改或完成更改)。
我该如何实现?
更新
我尝试了Radon的方法,但是当我插入以下行时:
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());
}
}
最佳答案
如果为图像设置了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()