2

I'm converting a project made with Borland C++Builder. There I have a class that manages messages for and from an electronic device. This class (call it MsgManager) encapsulate both a serial port and a tcpsocket, provides unified method and events no matter what kind of connection is used as long as some properties, and handle the whole protocol checks.

I want this class to be "global": so each of all my other classes have a pointer to the MsgManager, but also QML pages needs to use his methods and properties. The only thing that QML pages will not use are the various "events" (like a datareceived events or some error like timouts etc)

1) Is this a bad design for a QT applications? Seems that my old habits are sometime wrong in this new enviroment...

2)if no (or at least not THAT bad) how can i obtain this? I tried using qmlRegisterType<cMessageManager>("Phase.MessageManager", 1, 0, "MessageManager"); in main.cpp and then

MessageManager { id: msgman; }

in the mainForm.qml but i'm not able to "point" to the class from C++... and i'm not able to view the class from QML when i create it in c++

Thanks.

-EDIT- Adding code and asking for clarification:

@leemes: Thanks for the detailed (but noob-friendly :) ) answer.

I still have troubles.... this was my previous working code (even before trying to adding my new class):

#include <QtGui/QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include <QtQuick/QQuickView>   // Necessario per QQuickWindow

#include "ui_updater.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    qmlRegisterType<UI_Updater>("Phase.UI_Updater", 1, 0, "UI_Updater");
    QQmlApplicationEngine engine(QUrl("qrc:/qml/MainForm.qml"));
    QObject *topLevel = engine.rootObjects().value(0);
    QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
    if ( !window ) {
        qWarning("Error: Your root item has to be a Window.");
        return -1;
    }
    window->show();
    return app.exec();
}

I tried this changes:

#include <QtGui/QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include <QtQuick/QQuickView>   // Necessario per QQuickWindow

#include "ui_updater.h"

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

    // --- CHANGES TO TRY setContextProperty SOLUTION -------------------------
    //qmlRegisterType<UI_Updater>("Phase.UI_Updater", 1, 0, "UI_Updater");
    //QQmlApplicationEngine engine(QUrl("qrc:/qml/MainForm.qml"));

    UI_Updater*         ui_up;
    ui_up = new UI_Updater();

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("UI_Updater",ui_up);
    engine.setBaseUrl(QUrl("qrc:/qml/MainForm.qml"));
    //-------------------------------------------------------------------------

    QObject *topLevel = engine.rootObjects().value(0);
    QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
    if ( !window ) {
        qWarning("Error: Your root item has to be a Window.");
        return -1;
    }
    window->show();
    return app.exec();
}

But the debugger breaks somewhere in the disassembler window with a "segmentation fault" error. I see that i don't have the QQuickView (or QtQuickApplicationViewer) object you mentioned, and i can't recall why i ended up with the code i have now (but it was the only way i found to make it work :( )

So, could you help me a tiny bit again?

1

1 Answer 1

4

First of all, the type you want to export to the QML world needs to be accessible with the Qt meta object system in order to invoke functions of it in QML. That requires the type to inherit QObject and the functions to be slots (or "invokable methods" to be correct). You can also add "properties" in that classes (to use properties of the object in an expression), for this see the Q_PROPERTY macro.

Creating an instance in C++ and exporting its address to QML is a very common way to give the QML document the ability to invoke C++ methods "globally". There are a lot of use cases in which you want to do exactly that, so you're on the right path there.

If you want to export a type from C++ to QML which you want to instanciate there, you do this with type registration, like in your code snippet. But that's not what you actually want, since you want to create the instance in C++ and only give a pointer to QML.

If you want to export an instance of a type from C++ to QML, you do this with context properties:

MsgManager *instance = ...;
view->rootContext()->setContextProperty("msgman", instance);

where view is your QQuickView (or QtQuickApplicationViewer). Please note that this context property has to be set before setting the QML file name in order to be available from the very beginning.

See also: Embedding C++ Objects into QML with Context Properties


If you don't use a QQuickView but want to instantiate a Window (or ApplicationWindow) within QML, you typically use a QQmlEngine directly. A code loading a QML file after setting a root context property could look like this:

// QML engine:
QQmlEngine qml;
qml.rootContext()->setContextProperty("msgman", instance);  // <-- property

// Load main window (in my example qml/main.qml):
QQmlComponent windowComponent(&qml, QUrl::fromLocalFile("qml/main.qml"));
if (windowComponent.isError()) {
    for (auto error : windowComponent.errors())
        qDebug() << error;
    return 1;  // exit the main function immediately
}

// Some error checking and then casting the object to a window
QObject *object = windowComponent.create();
if (!object)
    qFatal("Failed to create an instance of main.qml!");
QQuickWindow *window = qobject_cast<QQuickWindow*>(object);
if (!window)
    qFatal("Top-level item in main.qml is not derived from QQuickWindow!");

// Finally show the window
window->show();

Note that this instance is never mentioned in QML other than accessing it (you don't have code such as MessageManager { id: msgman; } in your QML file). Simply use the name msgman as if there was code like that. Also, the instance will be available in all sub-documents you include (aka "components").

Example: You want to have a status display for your manager. It should display some property "ready" which you made available in the class, reporting if the device is ready for communication. For that you already declared the property with the Q_PROPERTY macro and now want to access it in QML:

MsgManagerStatus.qml:

import QtQuick 2.0

Text {
    text: msgman.ready ? "Device is ready." : "Device is not ready."
    color: msgman.ready ? "black" : "red"
}

One last thing to mention: If your QML document instantiates custom C++ types (custom visual items, C++ models, helper classes, ...), you can't access those context properties during construction of those classes like you could with QML components. Only after finishing construction, the class will have access to the QML context in which it is living. There are several workarounds for that, none of which is perfect. But I guess this topic is beyond your question. Just keep it in mind that instances of custom C++ types which are living in QML can access the QML context properties only after finishing construction.

1
  • Ok I see, you use a Window in QML and thus don't use the QQuickView class but an engine; that should work too. There is QQmlEngine and QQmlApplicationEngine. I use the former, you used the latter. See my edit (the part after the first line) to see how I do that; it might be the case that your version doesn't work correctly (yet I don't see why it shouldn't). Can you please try my version?
    – leemes
    Apr 16, 2014 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.