简体   繁体   English

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

[英]Receiving a signal with parameter from C++ class in QML

I would like to receive a signal from a C++ QObject class in QML I have read a guide from : 我想从QML中的C ++ QObject类接收信号,我已经阅读了以下指南:

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

but i am having trouble getting results here is my sample code: 但我在获取结果时遇到困难,这是我的示例代码:

myclass.h 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 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 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)
        }
    }
}

I get an error on QML stating 我收到关于QML的错误提示

Error: Cannot assign [undefined] to QString" 错误:无法将[undefined]分配给QString”

So I am guessing that i am doing the connections wrong. 所以我猜我在做连接错误。

You have the following errors: 您遇到以下错误:

  • According the docs the signals: They can never have return types (ie use void) . 根据文档 ,信号: 它们永远不能具有返回类型(即使用void) On the other hand it does not make sense that it is Q_INVOKABLE , and finally you must pass the value of the integer, not the reference. 另一方面,它是Q_INVOKABLE毫无意义,最后您必须传递整数值,而不是引用。

  • You have to export the QObject before loading the QML. 您必须在加载QML之前导出QObject。

*.h *。H

signals:
    void numberChanged(int number);

main.cpp main.cpp

...
QQmlApplicationEngine engine;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM