以下是使用QML制作一个带有开始和复位功能的秒表的示例代码:
import QtQuick 2.0
import QtQuick.Controls 2.15
Rectangle {
width: 300
height: 200
property int timeValue: 0
property bool isRunning: false
Timer {
id: timer
interval: 10
running: isRunning
repeat: true
onTriggered: {
timeValue += interval
}
}
Text {
id: timeText
text: formatTime(timeValue)
font.pixelSize: 30
anchors.centerIn: parent
function formatTime(ms) {
var seconds = Math.floor(ms / 1000)
var minutes = Math.floor(seconds / 60)
var hours = Math.floor(minutes / 60)
seconds %= 60;
minutes %= 60;
return (hours > 9 ? hours : "0" + hours) + ":" +
(minutes > 9 ? minutes : "0" + minutes) + ":" +
(seconds > 9 ? seconds : "0" + seconds);
}
}
Button {
text: isRunning ? "停止" : "开始"
onClicked: {
if (isRunning) {
timer.stop()
isRunning = false
text = "开始"
} else {
timer.start()
isRunning = true
text = "停止"
}
}
anchors {
topMargin: 20
horizontalCenterOffset:-50
}
}
Button {
text: "复位"
onClicked: {
timer.stop()
isRunning = false
timeValue = 0
timeText.text = formatTime(timeValue)
}
anchors {
topMargin: 20
horizontalCenterOffset:50
}
}
}
这个例子使用了一个Rectangle
作为容器,包含一个Timer
用于计时,一个显示时间的Text
组件以及两个按钮:一个用于开始/停止计时,另一个用于复位。通过点击按钮来控制计时的开始、停止和复位操作。
希望以上代码能够满足你的需求!
内容由零声教学AI助手提供,问题来源于学员提问