为了清楚地阐述我的
问题,我创建了一个小小的例子程序。这个程序是基于Qt5.3构建的,是一个QtQuick工程,大家可以
下载实测一下。
我使用Qt.createComponent()和Qt.createObject()来动态创建对象,在这个对象中我加入了粒子
系统,可以让其运行也可以不让其运行。结果发现即使使用someObject.destory()方法也无法让系统将该对象回收,结果导致严重的内存泄漏。
// TestObject.qml
import QtQuick 2.0
import QtQuick.Particles 2.0
Rectangle
{
id: root
width: 32
height: 32
color: "#" + ( Math.floor( Math.random( ) * 0xFFFFFFFF ) ).toString( 16 )
x: Math.random( ) * parent.width
y: Math.random( ) * parent.height
NumberAnimation on x { from: parent.width / 2; to: x }
NumberAnimation on y { from: parent.height / 2; to: y }
Timer
{
id: internalTimer
interval: 2000
repeat: false
onTriggered: root.destroy( )
}
ParticleSystem
{
id: system
anchors.centerIn: parent
running: root.parent.useParticle
ImageParticle
{
source: "qrc:///particleresources/star.png"
colorVariation: 0.2
}
Emitter
{
emitRate: 100
lifeSpan: 1000
size: 40
enabled: true
velocity: AngleDirection
{
angle: 360
angleVariation: 180
magnitude: 200
magnitudeVariation: 20
}
}
}
function startTimer( ) { internalTimer.start( ) }
}
下面是主程序:
import QtQuick 2.2
import QtQuick.Controls 1.1
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Check memory leak")
menuBar: MenuBar {
Menu
{
title: qsTr("Option")
MenuItem
{
id: qmlTestItem
checkable: true
checked: true
text: qsTr("dynamic
QML test")
}
MenuItem
{
id: useParticleItem
checkable: true
checked: false
text: qsTr( "use particle" )
}
}
}
Rectangle
{
id: qmlTestScene
anchors.fill: parent
color: "plum"
visible: qmlTestItem.checked
property bool useParticle: useParticleItem.checked
Button
{
anchors.centerIn: parent
text: qsTr( "click me to generate rectangle" )
property var testObject: Qt.createComponent( "TestObject.qml" )
onClicked:
{
var object = testObject.createObject( qmlTestScene );
object.startTimer( );
}
}
}
Text
{
anchors.right: qmlTestScene.right
anchors.bottom: qmlTestScene.bottom
text: qsTr( "made by jiangcaiyang, for test only" )
}
}
下面是程序的演示截图:

←内存在点击
按钮的时候一直在上升。
这里是源码,大家看看究竟有什么办法能够正确的回收对象从而避免内存泄漏。
内存泄漏的程序源码
CheckMemoryLeaks.7z (2 K) 下载次数:42