【问题标题】:Communication between C++ and QMLC++ 和 QML 之间的通信
【发布时间】:2011-08-08 06:21:30
【问题描述】:

这个page 展示了如何从 QML 中调用 C++ 函数。

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

我怎样才能做到这一点?

更新

我尝试了 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());
        }
    }

【问题讨论】:

  • 如果有人遇到此问题,则“错误:无法 dynamic_cast”可能是由于缺少标头包括“#include ”引起的。

标签: c++ qt qml


【解决方案1】:

因此,您可以将 C++ 对象设置为 C++ 中 QDeclarativeView 上的上下文属性,如下所示:

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

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    如果为图像设置objectName,则可以很容易地从 C++ 访问它:

    ma​​in.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()

    【讨论】:

      猜你喜欢
      • 2017-08-13
      • 2013-10-18
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多