繁体   English   中英

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

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

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

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的错误提示

错误:无法将[undefined]分配给QString”

所以我猜我在做连接错误。

您遇到以下错误:

  • 根据文档 ,信号: 它们永远不能具有返回类型(即使用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")));
...

暂无
暂无

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

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