2011-04-18 66 views
10

这个page显示了如何从QML中调用C++函数。C++和QML之间的通信

我想要做的是通过C++函数(触发状态更改或完成)更改按钮上的图像。

我该如何做到这一点?

UPDATE

我试图通过氡气的方法,但是立即当我插入该行:

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()); 
     } 
    } 
+1

如果有人遇到这种情况,“error:can not dynamic_cast”可能是由于包含“#include ”的头文件缺失导致的。 – Andrew 2014-01-21 14:49:09

回答

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()

5

所以,你可以设置你的C++对象的QDeclarativeView在C上下文属性++,就像这样:

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; 
    } 
} 

希望这有助于。