在 QML 中从 C++ class 接收带有参数的信号

Receiving a signal with parameter from C++ class in QML

我想从 QML 中的 C++ QObject class 接收信号我已经阅读了以下指南:

https://doc.qt.io/archives/qt-4.8/qtbinding.html#receiving-signals

但我在获取结果时遇到了问题,这里是我的示例代码:

myclass.h

class myClass : public QObject
 {
  Q_OBJECT

  public:

   explicit myClass(QObject *parent = nullptr);

   Q_INVOKABLE void incrementNumber(){
       number++;
       qDebug()<<number;
       emit numberChanged(number);
   }

  signals:
     Q_INVOKABLE int numberChanged(int &number);
  public slots:

  private:
     int number = 0;
  };

main.cpp

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QScopedPointer<myClass> myclass (new myClass);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    engine.rootContext()->setContextProperty("myclass",myclass.data());
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

QML

 Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")


    Button{
        onClicked: {
            myclass.incrementNumber()
        }
    }
    Text {
        id: texty
        text: "0"
    }

    Connections{
        target: myclass
        onNumberChanged: {
            texty.text = number
            console.log ("number Changed to: " + number)
        }
    }
}

我在 QML 上收到一个错误

Error: Cannot assign [undefined] to QString"

所以我猜我做错了连接。

您有以下错误:

  • 根据 docs 信号:它们永远不能有 return 类型(即使用 void)。另一方面,它是 Q_INVOKABLE 是没有意义的,最后你必须传递整数的值,而不是引用。

  • 您必须在加载 QML 之前导出 QObject。

*.h

signals:
    void numberChanged(int number);

main.cpp

...
QQmlApplicationEngine engine;

engine.rootContext()->setContextProperty("myclass", myclass.data());
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
...