Connect multiple signals and slot machines in Qt

advertisements

I'm teaching myself how to use Qt and I've reached a point where I need a number of signals/slots for when the user interacts with controls on a form.

I've managed to get signals and slots working but I would like to connect quite a number of signals and slots and for the sake of keeping my code manageable it would be nice to have them in their own separate function if at all possible.

So far I've had no luck moving them out of my main function here I've moved object to global successfully which seems to still work but doesn't help me much, from there trying to move engine or app has only resulted in errors. From what I can tell if I did attempt to connect them in a separate function the connections would just sort of collapse the second any such function returns.

Currently I have something that looks like this working:

int main(int argc, char *argv[])
  {
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    QObject *object = engine.rootObjects()[0];

    controls myClass;
    QObject::connect(object, SIGNAL(taskComplete(int)), &myClass, SLOT(taskComplete(int)));

    return app.exec();
  }

What options do I have so that I don't have to just cram it all into main?

Disclaimer: I have had very little luck figuring out my way around Qt so far and as such I have no idea what I am doing so if I'm completely barking up the wrong tree I'd like to know.


In the case of things happening in QML and needing to be handled in C++, it has proven advantegous to handle the "connect" on the QML side.

Basically your C++ code would expose one or more QObject based objects to QML, e.g. via setContextProperty() of the engine's root context and the QML code would just call their slots when every it needs to.

Main reason is that this doesn't impose too many details on our QML code, e.g. certain structure, certain objects with specific names or signals, etc. The C++ side provides the functionality, the QML side calls it when it needs to.