无法在单例中创建某些 QML 类型 [英] Cannot create certain QML types in a singleton

查看:30
本文介绍了无法在单例中创建某些 QML 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于样式定义的 QML 单例,定义如下:

I have a QML singleton for use in styling defined as follows:

pragma Singleton
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Controls.Styles 1.1

QtObject {
    property ProgressBarStyle progressBarErrorStyle: ProgressBarStyle {
        background: Rectangle {
            radius: 2
            color: "lightgray"
            border.color: "gray"
            border.width: 1
            implicitWidth: 200
            implicitHeight: 20
        }
        progress: Rectangle {
            color: "orangered"
            border.color: "red"
        }
    }
}

我可以导入对象并使用它,但是 progressBarErrorStyle 总是被赋予 ProgressBarStyle_QMLTYPE_17 类型.如果我将其更改为 Rectangle,则正确键入为 QQuickRectangle.

I'm able to import the object and use it, however progressBarErrorStyle is always given the type ProgressBarStyle_QMLTYPE_17. If I change it to a Rectangle, then it is correctly typed as QQuickRectangle.

QtQuick.Controls.Styles 导入定义了 ProgressBarStyle,并且在 QtCreator 中我没有收到任何语法错误......那么为什么我的对象被赋予了错误的类型在运行时?

The QtQuick.Controls.Styles import defines ProgressBarStyle, and in QtCreator I'm not getting any syntax errors... so why is my object given the wrong type at runtime?

推荐答案

你应该使用 Component 作为属性类型:

You should use Component as the property type:

import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.2

Rectangle {
    property Component progressBarErrorStyle: ProgressBarStyle {
        background: Rectangle {
            radius: 2
            color: "lightgray"
            border.color: "gray"
            border.width: 1
            implicitWidth: 200
            implicitHeight: 20
        }
        progress: Rectangle {
            color: "orangered"
            border.color: "red"
        }
    }

    ProgressBar {
        id: progressBar

        NumberAnimation {
            target: progressBar
            property: "value"
            to: 1
            running: true
            duration: 2000
        }

        style: progressBarErrorStyle
    }
}

样式组件在 Loader 项目内部使用,它们在需要时创建组件的实例,就像 Qt Quick 的 ListView,例如.

The components for styles are used in Loader items internally, which create instances of the components when they need to, just like delegates in Qt Quick's ListView, for example.

这篇关于无法在单例中创建某些 QML 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆