外部二进制资源已打开,但QML中不存在



我有以下main.qml文件:

import QtQuick 2.5
import QtQuick.Controls 1.4
Item
{
    anchors.centerIn: parent
    Label
    {
        id: textLabel
        anchors.fill: parent
        x: 200
        y: 400
    }
    CustomObject
    {
        id: customObjectId
    }
}

CustomObject是在外部二进制资源中定义的QML文件,由rcc命令生成:

rcc -binary -o redTheme.qrc redTheme.rcc

CustomObject.qml

import QtQuick 2.5
import QtQuick.Controls 1.4
Item
{
    Rectangle
    {
        width: 200
        height: 120
        color: "blue"
        Label
        {
            text: "customObject"
        }
    }
}

C++端,我注册资源如下:

QResource::registerResource(QCoreApplication::applicationDirPath() + "/data/themes/redTheme.rcc");

函数返回true,这意味着文件已打开。

然而,CustomObject并不存在于我的main.qml文件中。为什么?

CustomObject is not a type

EDIT:我已经将CustomObject封装到QML Module中,然后将其编译到.rcc文件中(这意味着qmldir文件位于.qrc内部)。没有任何区别,即使我添加了import语句(import redTheme 1.0),CustomObject仍然不能被识别为类型。我的qmldir文件的内容:

module redTheme
CustomObject 1.0 CustomObject.qml

我不能100%确定,但我认为QML文件作为类型只适用于"内部"QML文件,即内部资源文件中的QML文件。

为了使外部QML文件作为类型工作,您需要定义一个有效的QML模块及其qmldir文件等。也可以使用C++API将其公开为一种类型,但我还没有对其进行研究,基本上,qmldir文件解析器就是这样做的。

使用外部QML文件的另一种方式是作为path/url,也就是说,如果您想实例化它,您要么需要使用Loader,要么手动动态实例化它。

这可能有助于将外部QML文件注册为QML类型:

int qmlRegisterType(const QUrl &url, const char *uri, int versionMajor, int versionMinor, const char *qmlName)

此函数在QML系统中注册一个具有名称的类型qmlName,在从具有版本号的uri导入的库中由versionMajor和versionMinor组成。类型由定义位于url的QML文件。url必须是绝对url,即。url.isRelative()==false。

通常,QML文件可以作为类型直接从其他QML加载文件,或使用qmldir文件。此功能允许注册文件到C++代码中的类型,例如当类型映射需要在启动时按程序确定。

我在外部rcc文件中也遇到过类似的效果。当从外部资源加载qml文件时,尝试将"qrc"方案添加到您的url:

QQmlApplicationEngine engine("qrc:/main.qml");

最新更新