Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.

Receiving signals with arguments in QML from C++

From Qt Wiki
Revision as of 13:07, 28 November 2016 by EdwardWelbourne (talk | contribs) (Sub-categorize)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
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);
 }
}