Change ownership for value type property
According to Qt documentation:
Quote:
Data Ownership
When data is transferred from C++ to QML, the ownership of the data always remains with C++. The exception to this rule is when a QObject is returned from an explicit C++ method call: in this case, the QML engine assumes ownership of the object, unless the ownership of the object has explicitly been set to remain with C++ by invoking QQmlEngine::setObjectOwnership() with QQmlEngine::CppOwnership specified.
It means that call of getter function of properties doesn't change ownership.
When i have some derived from QObject class with properties of simple type(int, QString...), registered in QML (via qmlRegisterSingletonType) and used as CppOwnership instance.
Code:
{
Q_OBJECT
public:
Q_PROPERTY (QColor color READ colorValue NOTIFY colorChanged
) {
return m_color;
}
signals:
void colorChanged();
private:
};
And QML main window:
Code:
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQuick.Dialogs 1.1
import QtQuick.Layouts 1.0
]import QtQuick.Window 2.12
import Qt.labs.platform 1.1
import QtQml 2.12
import QtQuick.Shapes 1.12
import customdraw 1.0
Window {
id: wnd
width: 640
height: 480
visible: true
Button {
anchors.fill: parent
onClicked: {
var f = TCustomDraw.color
}
}
}
What happens with ownership of color object when i press the Button ?
If ownership of color object remains in c++ does it mean a memory leakage ?
Re: Change ownership for value type property
Re: Change ownership for value type property
Quote:
What happens with ownership of color object when i press the Button ?
If ownership of color object remains in c++ does it mean a memory leakage ?
You are confusing C++ instance lifetime with Qt QObject ownership lifetime. They aren't the same. C++ instances aren't owned by anything. They exist until whatever execution process they are created in goes out of scope, like in this case the function call to the color property. As soon as that function call exits, the QColor instance goes out of scope. The value held by that QColor instance is copied to the variable "f" in the QML code, and as soon as that statement ends the copy of m_color goes away, no memory leak.
The QColor returned by the color property is returned by value, meaning it is placed on the stack as a copy of m_color. As soon as that instance goes out of scope, it is destroyed automatically. The QColor class is not derived from QObject. There is no concept of Qt ownership in the sense of other classes derived from QObject (such as QWidget, etc.).
In this case, the QColor might as well be a fundamental type such as int or double. There is no magic going on, no transfer of ownership, no memory leak. The only way a memory leak could occur is if a method returned a pointer to an instance created by new() during the function call, and that pointer wasn't stored and later deleted on the receiving end.