error.h

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#pragma once

#include <QObject>
#include <QQmlEngine>

class Error {
    Q_GADGET
    Q_ENUMS(Type)
    Q_PROPERTY(Type type READ type WRITE setType)
public:
    enum class Type { NoError, Fatal };

    static void RegisterType() {
        qmlRegisterUncreatableType<Error>(
                "My.Error", 1, 0, "Error", "can not creatable");
    }

    Type type() const {
        return type_;
    }

    void setType(Type type) {
        type_ = type;
    }

private:
    Type type_;
};

Q_DECLARE_METATYPE(Error::Type)

send_error.h

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#pragma once
#include <QObject>

#include "error.h"
class SendError : public QObject {
    Q_OBJECT
public:
    using QObject::QObject;

public:
    Q_INVOKABLE void sendFailed();

signals:
    void failed(Error::Type error, const QString& message);
};

send_error.cpp

1
2
3
4
5
6
#include "senderror.h"

void SendError::sendFailed() {
    emit failed(Error::Type::Fatal, "this is fatal error");
}

main.qml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import QtQuick 2.12
import QtQuick.Window 2.12
import My.Error 1.0
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Connections {
        target: sendError
        onFailed: function(type, message) {
            if (type === Error.Fatal) {
                console.log("type is fatal")
            } else if (type === Error.NoError) {
                console.log("type is no error")
            }
        }
    }

  MouseArea {
      anchors.fill: parent
      onClicked: {
          sendError.sendFailed()
      }
  }
}