[英]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.