QtQuick:从C ++创建组件

时间:2014-06-04 07:00:40

标签: c++ qt qt5 qt-quick qtquick2

我遇到QQuickView从C ++实例化组件的问题......这是我的代码:

班级定义(vviewerqml.h):

class VViewerQml : public QObject
{
    Q_OBJECT

public:
    explicit VViewerQml(QSettings &systemSettings, QObject *parent = 0);
    ~VViewerQml();

protected slots:
    void onViewStatusChanged(QQuickView::Status status);

protected:
    QString _qmlFolder;
    QQuickView _view;
};

类实现(vviewerqml.cpp):

#include "vviewerqml.h"

VViewerQml::VViewerQml(QSettings &systemSettings, QObject *parent) :
    QObject(parent)
{
    // Initialize viewer reading from settings file
    _qmlFolder = "/my/path/to/qml/files";

    // Initialize the source
    connect(&_view, SIGNAL(statusChanged(QQuickView::Status)),
        this, SLOT(onViewStatusChanged(QQuickView::Status)));

    _view.setSource(QUrl::fromLocalFile(QDir(_qmlFolder).filePath("Main.qml")));

    // Show the viewer
    _view.show();
}

VViewerQml::~VViewerQml()
{
    // Close the viewer
    _view.close();
}

void VViewerQml::onViewStatusChanged(QQuickView::Status status)
{
    if(status == QQuickView::Ready)
    {
        QQmlComponent *c =
            new QQmlComponent(_view.engine(),
            QDir(_qmlFolder).filePath("TextLegacy.qml"));

        QQuickItem *i = qobject_cast<QQuickItem*>(c->create());
        QQmlEngine::setObjectOwnership(i, QQmlEngine::CppOwnership);
        i->setParent(_view.rootObject());
        i->setVisible(true);
    }
}

这是我的Main.qml

import QtQuick 2.0

Rectangle {
    width: 1024
    height: 768
    color: "#000000"

    Text {
        x: 0
        y: 0
        color: "#ffffff"
        text: "Main page"
    }
}

这是我的TextLegacy.qml

import QtQuick 2.0

Item {
    Rectangle {
        x: 0
        y: 0
        width: 100
        height: 50
        color: "#ff0000"
    }
}

我的代码正常工作,直到加载Main.qml:QML查看器在屏幕上打开,我可以阅读文本&#34;主页&#34; (在屏幕上显示黑色)...但不幸的是我无法加载TextLegacy.qml ...如果我在onViewStatusChanged函数中放置一个断点,执行到达那一点......调试控制台中显示可见错误...但我无法在屏幕上看到TextLegacy.qml提供的红色矩形......

我错过了什么?有人能帮忙吗?

1 个答案:

答案 0 :(得分:4)

好的,我自己找到了解决方案:我将setParentsetParentItem混淆了......正确的代码是:

void VViewerQml::onViewStatusChanged(QQuickView::Status status)
{
    if(status == QQuickView::Ready)
    {
        QQmlComponent *c = new QQmlComponent(_view.engine(),
            QUrl::fromLocalFile(QDir(_qmlFolder).filePath("TextLegacy.qml")));
        QQuickItem *i = qobject_cast<QQuickItem*>(c->create());
        QQmlEngine::setObjectOwnership(i, QQmlEngine::CppOwnership);
        i->setParent(this);
        i->setVisible(true);
        i->setParentItem(_view.rootObject());
    }
}

实际上i->setParent(this);i的父级定义为QObject(例如,用于删除目的),而i->setParentItem(_view.rootObject());实际上将对象添加到场景中,作为孩子场景根对象。