C++ 之间的通信和QML
此页面展示了如何从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());
}
}
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<QObject *>(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<QObject *>(viewer.rootObject());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你为图像设置一个
objectName
,你可以很容易地从C++访问它:main.qml
在C++中:
→QObject.findChild(), QObject.setProperty()
If you set an
objectName
for the image, you can access it from C++ quite easy:main.qml
in C++:
→ QObject.findChild(), QObject.setProperty()
因此,您可以将 C++ 对象设置为 C++ 中 QDeclarativeView 的上下文属性,如下所示:
在
ImageChanger
类中,声明一个信号,如:void updateImage(QVariant imgSrc);
然后当你想改变图像时,调用
emit updateImage(imgSrc);
。现在,在您的 QML 中,按如下方式收听此信号:
希望这会有所帮助。
So, you could set your C++ object as a context property on the QDeclarativeView in C++, like so:
In your
ImageChanger
class, declare a signal like:void updateImage(QVariant imgSrc);
Then when you want to change the image, call
emit updateImage(imgSrc);
.Now in your QML, listen for this signal as follows:
Hope this helps.