Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

findChild and loader



  • Hi,

    I need to interact with QML objects from C++. I do this via getting the pointer to the object like this:

    parent->findChild<QObject*>(QString::fromStdString(childObjectName));
    

    where childObjectName is the objectName property of the qml item. Now I moved this QML item into a quick controls 1 TabView which is using a loader. So now the object is not present and findChild thus returns a null pointer. What is the best way to work around this?



  • Hi @maxwell31, which type of interaction would you like to have with the childObjectName? I don't personally like or recommend to do what you are trying to do because it kinda destroys the MVC pattern QML provide us. I would rather expose a class to QML (for each state or view) and then from QML directly call functions or update properties from this exposed class.



  • I have a multi threaded application. In the data thread I hold variables which control application behaviour. I want to be able to set those variables via gui controls. what I tried to do is create qml components, e.g. text fields which will be automatically updated if the variable changes in the data thread, and also the other way, if the user updates this variable the new value is passes to the data thread, and the variable is updated. for this I need to register the qml component (text field with signals) with an update handler, which will listen to signals from the textfield or also set the value of the text field directly if an update happens in the data thread.



  • @maxwell31 Have you take a look at QQmlContext and Q_PROPERTY?
    https://doc.qt.io/qt-5/qqmlcontext.html
    https://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html
    You can expose C++ attributes to your QML files and use them as you like. They also update their value with the special valueChanged signal.



  • Yes, I know the Q_PROPERTY, I wanted to avoid using them, as there might be really many input fields, and I wanted to avoid writing the code for all of them



  • @maxwell31 It sounds like what @rrlopez suggested earlier is the right way to go. You need to expose your data via a C++ model.


Log in to reply