Qt - 使用Loader

时间:2017-03-30 11:43:52

标签: c++ qt memory-leaks qml loader

首先,我想为我2个月前开始学习的糟糕英语道歉。

现在我的问题。我想使用组件Loader来动态更改视图文件。一切正常,但在Loader中更改源变量时会发生内存泄漏。我认为我的代码不是一个错误,但我不知道它为什么会发生。

我在Qt论坛上问过,但没有人回答我。

我使用Qt版本5.8,Windows 7

我相信你理解我的英语。 谢谢你的帮助

这是一个发生内存泄漏的小例子。 http://www.filedropper.com/untitled2_1

或者这是源代码:

的main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlComponent>
#include "testtimer.h"
#include <QQmlContext>
#include <QVariant>
#include <QObject>
#include <QTimer>
int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine *_engine = new QQmlApplicationEngine();
    QQmlComponent* _myComponent = new QQmlComponent(_engine, _engine);
    TestTimer test;
    QTimer *timer = new QTimer(&test);
    QObject::connect(timer,SIGNAL(timeout()),&test,SLOT(changeFile()));
    timer->start(10);
    _myComponent->loadUrl(QUrl(QStringLiteral("qrc:/main.qml")));
    _engine->rootContext()->setContextProperty("test",&test);
    QObject* _myComponentObj = _myComponent->create();
    return app.exec();
}

testtimer.cpp

#include "testtimer.h"

TestTimer::TestTimer(QObject *parent) : QObject(parent)
{

}

QUrl TestTimer::urlFile(){
    return _urlFile;
}

void TestTimer::changeFile(){
    if(page1)
        _urlFile=QUrl(QLatin1String("qrc:/Page2.qml"));
    else
        _urlFile=QUrl(QLatin1String("qrc:/Page1.qml"));
    page1=!page1;
    emit urlFileChanged();
}

main.qml

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Loader{
        source: test.urlFile
        onSourceChanged: gc()
    }
}

Page1.qml和Page2.qml(页面只有相同的内容,每个页面都有不同颜色的矩形):

import QtQuick 2.7

Rectangle{
    width:600
    height:600
    color:"red"
}

0 个答案:

没有答案