首页 > 解决方案 > 将自定义控件移动到自己的文件中时出现 QML TypeError

问题描述

我已经按照文档成功地设计了一个 QML Switch,它运行良好。我现在想重用我的样式开关,但是当我将开关代码移动到它自己的文件中时,我得到了这些错误:

qml/QtQuick/Controls/Switch.qml:124: TypeError: Cannot read property 'max' of null
qml/QtQuick/Controls/Switch.qml:123: TypeError: Cannot read property 'min' of null
qml/QtQuick/Controls/Switch.qml:122: TypeError: Cannot read property '__handle' of null
MySwitch.qml:28: TypeError: Cannot read property 'switchStyle' of undefined

MySwitch 代码如下:

import Felgo 3.0
import QtQuick 2.12
import QtQuick.Layouts 1.12
import QtQuick.Controls 2.12 as Q

Q.Switch {
    id: switchControl
    indicator: Rectangle {
        implicitWidth: 48 +textOff.width - 5
        implicitHeight: 26
        x: parent.leftPadding  //sc
        y: parent.height / 2 - height / 2
        radius: 13
        color: parent.checked ? "black" : "white"  //sc
        border.color: "black"
        // Control center circle
        Rectangle {
            x: parent.parent.checked ? parent.width - width : 0
            width: 26
            height: 26
            radius: 13
            color: "white"
            border.color: "black"
        }  // <-- This is line 28

        // On text
        MultiResolutionImage {
            anchors.verticalCenter: parent.verticalCenter
            x: 13 -5
            fillMode: Image.PreserveAspectFit
            source: "../../assets/img/scenesettings/texton.png"
            visible: parent.checked  //sc
        }

        // Off text
        MultiResolutionImage {
            id: textOff
            anchors.verticalCenter: parent.verticalCenter
            x: parent.width - textOff.width - 13 + 5 // Outside of radius
            fillMode: Image.PreserveAspectFit
            source: "../../assets/img/scenesettings/textoff.png"
            visible: !parent.checked  // switchControl
        }
    }  // Indicator    
}  // Switch

有人可以解释什么是错的吗?

标签: qtqmlcontrols

解决方案


为防止名称冲突,您可以使用as关键字为导入添加前缀名称,如下所示:

import Felgo 3.0 as MyLibrary

然后为了使用该模块中的任何内容,您将需要使用该名称:

MyLibrary.MultiResolutionImage {
   ...
}

推荐阅读