QML 引用错误
QML reference errors
我有一个小型 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 is not defined"
为 main.qml 中的 NumComponent 提供一个 id:
NumComponent{
id: numComponent
} //my component written in NumComponent.qml
将您的 onClicked 处理程序更改为:
numComponent.startTimer();
另一种变体:
添加到您的号码正一个 属性 别名:
property alias timed: numberTimer.running
将 main 中的 onClicked 处理程序更改为:
numComponent.timed = !numComponent.timed;
在您的根项目中添加 NumComponent.qml:
函数启动定时器(){
numberTimer.start();
}
现在您可以启动和停止计时器了。
我有一个小型 QML 项目,但我遇到了 qml 组件引用问题。所以我试图从 main.qml.
中的 startButton 启动 NumComponent.qml 的 numberTimermain.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 is not defined"
为 main.qml 中的 NumComponent 提供一个 id:
NumComponent{ id: numComponent } //my component written in NumComponent.qml
将您的 onClicked 处理程序更改为:
numComponent.startTimer();
另一种变体:
添加到您的号码正一个 属性 别名:
property alias timed: numberTimer.running
将 main 中的 onClicked 处理程序更改为:
numComponent.timed = !numComponent.timed;
在您的根项目中添加 NumComponent.qml:
函数启动定时器(){ numberTimer.start(); }
现在您可以启动和停止计时器了。