我有一个小型的QML项目,我遇到了qml组件引用的问题。所以我试图从main.qml中的startButton启动NumComponent.qml的numberTimer。
main.qml
import QtQuick 2.7
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
NumComponent{} //my component written in NumComponent.qml
Rectangle{
id: startButton
anchors.centerIn: parent
height: parent.height * 0.2
width: height
color: "lightblue"
MouseArea{
anchors.fill: parent
onClicked: {
numberTimer.start();
}
}
}
}
NumComponent.qml
import QtQuick 2.0
Rectangle {
id: numberRect
color: "red"
height: parent.height * 0.4
width: height
Text{
id: numberText
anchors.centerIn: parent
text: ""
}
Timer{
id: numberTimer
interval: 100
repeat: true
onTriggered: {
numberText.text = Math.floor(Math.random() * 8);
}
}
}
我收到此错误:“qrc:/main.qml:22:ReferenceError:numberRect未定义”
答案 0 :(得分:2)
在main.qml中为您的NumComponent提供一个id:
NumComponent{
id: numComponent
} //my component written in NumComponent.qml
将onClicked处理程序更改为:
numComponent.startTimer();
另一种变体:
添加到您的numberRect属性别名:
property alias timed: numberTimer.running
将main中的onClicked处理程序更改为:
numComponent.timed =!numComponent.timed;
添加到根项目中的NumComponent.qml:
function startTimer(){ numberTimer.start(); }
现在您可以启动和停止计时器了。