Skip to content Skip to sidebar Skip to footer

Qml Findchild From A Different Component

The objective: I'm writing a Gui front-end for a Matplotlib-based library for nested samples (pip install anesthetic if you want to have a look). How I would go about it in C++: My

Solution 1:

Component is used to define a QML element, it does not instantiate it, therefore you cannot access the object. Creating a Figure.qml is equivalent to creating a Component, and you are creating a Component inside another Component.

The solution is not to use Component:

Figure.qml

import QtQuick.Controls 2.12import QtQuick 2.12

Rectangle{ 
    objectName: "figure"
}

But it is not recommended to use objectName since, for example, if you create multiple components, how will you identify which component it is? o If you create the object after a time T, or use Loader or Repeater you will not be able to apply that logic. Instead of them it is better to create a QObject that allows obtaining those objects:

from PySide2 import QtCore
import shiboken2


classObjectManager(QtCore.QObject):
    def__init__(self, parent=None):
        super().__init__(parent)
        self._qobjects = []

    @propertydefqobjects(self):
        return self._qobjects

    @QtCore.Slot(QtCore.QObject)defadd_qobject(self, obj):
        if obj isnotNone:
            obj.destroyed.connect(self._handle_destroyed)
            self.qobjects.append(obj)
        print(self.qobjects)

    def_handle_destroyed(self):
        self._qobjects = [o for o in self.qobjects if shiboken2.isValid(o)]
# ...
object_manager = ObjectManager()
context = engine.rootContext()
context.setContextProperty("object_manager", object_manager)
qmlFile = Path(Path.cwd(), Path(__file__).parent, "view.qml")
engine.load(QtCore.QUrl.fromLocalFile(str(qmlFile)))
# ...
import QtQuick.Controls 2.12import QtQuick 2.12

Rectangle{ 
    Component.onCompleted: object_manager.add_qobject(this)
}

Post a Comment for "Qml Findchild From A Different Component"