Receiving signals with arguments in QML from C++: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
(Sub-categorize) |
||
(5 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
[[Category: | {{Outdated|reason=Qt Quick 1}} | ||
[[Category:Snippets::QML]] | |||
The example code below shows how you can receive signals with arguments in QML from C++. The important thing to notice in the example is that the signal's argument needs to be named identically in QML and in C++. So in this example it needs to be referred to as "text" both places, otherwise you will receive errors. | |||
main.cpp | |||
<code> | <code> | ||
#include <QtGui> | #include <QtGui> | ||
Line 14: | Line 13: | ||
Q_OBJECT | Q_OBJECT | ||
public: | public: | ||
Q_INVOKABLE void triggerEvent(QString text) { | |||
Q_INVOKABLE void triggerEvent(QString text) | emit somethingHappened(text); | ||
} | } | ||
Person() | Person() { | ||
startTimer(1000); | |||
} | } | ||
void timerEvent(QTimerEvent | void timerEvent(QTimerEvent *e) { | ||
QString text = "The text"; | |||
triggerEvent(text); | |||
} | } | ||
signals: | signals: | ||
Line 33: | Line 28: | ||
#include "main.moc" | #include "main.moc" | ||
int main(int argc, char | |||
int main(int argc, char** argv) | |||
{ | { | ||
QApplication app(argc, argv); | QApplication app(argc, argv); | ||
Line 44: | Line 40: | ||
} | } | ||
</code> | </code> | ||
main.qml | main.qml | ||
<code> | <code> | ||
import People 1.0 | import People 1.0 | ||
Line 52: | Line 50: | ||
id: myPerson | id: myPerson | ||
onSomethingHappened: { | onSomethingHappened: { | ||
console.log(" something happened " +text); | |||
} | } | ||
} | } | ||
</code> |
Latest revision as of 13:07, 28 November 2016
IMPORTANT: The content of this page is outdated. Reason: Qt Quick 1 If you have checked or updated this page and found the content to be suitable, please remove this notice. |
The example code below shows how you can receive signals with arguments in QML from C++. The important thing to notice in the example is that the signal's argument needs to be named identically in QML and in C++. So in this example it needs to be referred to as "text" both places, otherwise you will receive errors.
main.cpp
#include <QtGui>
#include <QtDeclarative>
class Person : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE void triggerEvent(QString text) {
emit somethingHappened(text);
}
Person() {
startTimer(1000);
}
void timerEvent(QTimerEvent *e) {
QString text = "The text";
triggerEvent(text);
}
signals:
void somethingHappened(QString text);
};
#include "main.moc"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
qmlRegisterType<Person>("People", 1, 0, "Person");
QDeclarativeView view;
view.setSource(QUrl::fromLocalFile("main.qml"));
view.resize(200,100);
view.show();
return app.exec();
}
main.qml
import People 1.0
import QtQuick 1.0
Person {
id: myPerson
onSomethingHappened: {
console.log(" something happened " +text);
}
}