QML:在 QML 中使用 cpp 信号总是导致“无法分配给不存在的属性";

2022-01-19 00:00:00 signals qt qml c++

我只是想将一个 cpp 信号连接到一个 qml 插槽并尝试了不同的方法,但它总是在运行时导致相同的 QML 错误:无法分配给不存在的属性onProcessed"!为什么?

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?

这是我的 Cpp 对象:

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

这是我的 main.cpp

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

这是我的 QML 文件

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

我将 QT 5.3.0 与 Qt Creator 3.1.1 一起使用,这甚至提示我 onProcessed 并正确突出显示它.

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

推荐答案

要从 C++ 对象中公开信号,您必须遵循一些命名约定:

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

  • 信号在 C++ 代码中必须以小写字母开头,即 void yourLongSignal()
  • QML 中的信号处理程序将被命名为 on

所以,您唯一需要在代码中编辑的就是更改

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

signals:
    void processed(const QString& str);

相关文章