QML: Using cpp signal in QML always results in “Ca

2019-05-06 15:34发布

问题:

I just want to connect a cpp signal to a qml slot and tried different ways, but it always results in the same QML-Error at runtime: Cannot assign to non-existent property "onProcessed"! Why?

This is my Cpp Object:

#include <QObject>

class ImageProcessor : public QObject
{
    Q_OBJECT
public:
    explicit ImageProcessor(QObject *parent = 0);

signals:
    void Processed(const QString str);
public slots:
    void processImage(const QString& image);
};

ImageProcessor::ImageProcessor(QObject *parent) :
    QObject(parent)
{
}

void ImageProcessor::processImage(const QString &path)
{
    Processed("test");
}

This is my main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQml>

#include "imageprocessor.h"

int main(int argc, char *argv[])
{
    qmlRegisterType<ImageProcessor>("ImageProcessor", 1, 0, "ImageProcessor");

    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

    return app.exec();
}

And this is my QML file

import QtQuick 2.2
import QtQuick.Window 2.1
import QtMultimedia 5.0

import ImageProcessor 1.0

Window {
    visible: true
    width: maximumWidth
    height: maximumHeight

    Text {
        id: output
        text: qsTr("Hello World")
        anchors.centerIn: parent
    }

    VideoOutput {
        anchors.fill: parent
        source: camera
    }

    Camera {
        id: camera
        // You can adjust various settings in here

        imageCapture {
            onImageCaptured: {
                imageProcessor.processImage(preview);
            }
        }
    }

    MouseArea {
        anchors.fill: parent
        onClicked: {
            camera.imageCapture.capture();
        }
    }

    ImageProcessor{
        id: imageProcessor
        onProcessed: {
            output.text = str;
        }
    }
}

I am using QT 5.3.0 with Qt Creator 3.1.1, which is even suggesting me onProcessed and highlights it correctly.

回答1:

For exposing signals from C++ Object you must follow some naming conventions:

  • Signal must begin by a lowercase letter in your C++ code, i.e void yourLongSignal()
  • Signal handler in QML will be named on<YourLongSignal>

So, the only thing you have to edit in your code is to change

signals:
    void processed(const QString& str);


标签: c++ qt signals qml