Connecting a complex signal from QML to Qt

The example code below shows how you can connect complex signals from QML to Qt.

main.cpp

  1. #include <QtGui>
  2. #include <QtDeclarative>
  3.  
  4. class DeclarativeView : public QDeclarativeView
  5. {
  6.  Q_OBJECT
  7. public:
  8.  DeclarativeView(const QUrl & source) : QDeclarativeView(source)
  9.  {}
  10.  public slots:
  11.   void testSlot(QString string1, QString string2)
  12.   {
  13.    qDebug() << string1 <<  string2;
  14.   }
  15. };
  16.  
  17. #include "main.moc"
  18. int main(int argc, char **argv)
  19. {
  20.     QString file = "main.qml";
  21.  
  22.     QApplication app(argc, argv);
  23.     DeclarativeView view(QUrl::fromLocalFile(file));
  24.  
  25.     QDeclarativeItem *item = qobject_cast<QDeclarativeItem *>(view.rootObject());
  26.  QObject::connect(item, SIGNAL(viewClicked(QString , QString)), &view, SLOT(testSlot(QString, QString)));
  27.  
  28.  view.resize(200,200);
  29.     view.show();
  30.     return app.exec();
  31. }

main.qml

  1. import QtQuick 1.0
  2.  
  3. Item {
  4.     width: 200; height: 300
  5.     signal viewClicked(string first, string second)
  6.    
  7.     MouseArea {
  8.  anchors.fill: parent
  9.  onClicked: viewClicked("first", "second")
  10.     }
  11. }

Categories: