06. 定时器
一、定时器
QML 有一个 Timer元素,它允许你在 QML 中设置定时器。这个元素是 Qt Quick 模块的一部分。我们可以通过定时器的 interval 属性设置 定时间隔,通过 running 属性设置 定时器默认是否运行,通过 repeat 属性设置 定时器是否可以重复触发。在设置完相关属性后,我们还可以通过 start() 开发 启动定时器,通过 stop() 方法 停止定时器。
我们可以在终端中使用 pip 安装 PySide6 模块。默认是从国外的主站上下载,因此,我们可能会遇到网络不好的情况导致下载失败。我们可以在 pip 指令后通过 -i 指定国内镜像源下载。
pip install pyside6 -i https://mirrors.aliyun.com/pypi/simple
国内常用的 pip 下载源列表:
- 阿里云 https://mirrors.aliyun.com/pypi/simple
- 清华大学 https://pypi.tuna.tsinghua.edu.cn/simple
- 中国科学技术大学 http://pypi.mirrors.ustc.edu.cn/simple
我们新建一个 template.py 文件。
import sys
from PySide6.QtWidgets import QApplication
from PySide6.QtQml import QQmlApplicationEngine
if __name__ == "__main__":
app = QApplication(sys.argv) # 1.创建一个QApplication类的实例
engine = QQmlApplicationEngine() # 2.创建QML引擎对象
engine.load("template.qml") # 3.加载QML文件
sys.exit(app.exec()) # 4.进入程序的主循环并通过exit()函数确保主循环安全结束
我们新建一个 template.qml 文件。
import QtQuick.Window
import QtQuick.Controls
// Window控件表示一个顶级窗口
// 在QML中,元素是通过大括号{}内的属性来配置的。
Window {
id: windowId
width: 800 // 窗口的宽度
height: 600 // 窗口的高度
visible: true // 显示窗口
color: "lightgray"
property int count: 0 // 定义一个属性,用于计数
// 在矩形内部定义一个文本(Text)元素。这意味着文本将作为矩形的一个子元素,通常会被绘制在矩形内部。
Text {
anchors.centerIn: parent // 将中心的锚点位到父元素的中心
font.pointSize: 32 // 设置文本的字体大小
text: "Value:" + windowId.count // 设置文本元素的内容
}
// 定义一个按钮
Button{
id: startButtonId // 定义一个标识
width: 200 // 按钮的宽度
height: 50 // 按钮的高度
// 使用锚点(anchors)系统来定位文本元素
anchors.left: parent.left // 将左边的锚点定位到父元素的左边
anchors.leftMargin: 20 // 设置左侧边距为20像素
anchors.bottom: parent.bottom // 将底部的锚点定位到父元素的底部
anchors.bottomMargin: 20 // 设置底部边距为20像素
text: "开始加载" // 按钮的文本
// 按键点击时触发
onClicked: {
if (startButtonId.text == "开始加载") {
windowId.count = 0 // 重置计数
timerId.start() // 开启定时器
startButtonId.text = "暂停加载"
} else if (startButtonId.text == "暂停加载") {
timerId.stop()
startButtonId.text = "继续加载"
} else if (startButtonId.text == "继续加载") {
timerId.start()
startButtonId.text = "暂停加载"
}
}
}
Button{
width: 200 // 按钮的宽度
height: 50 // 按钮的高度
anchors.right: parent.right // 将右边的锚点定位到父元素的右边
anchors.rightMargin: 20 // 设置右侧边距为20像素
anchors.bottom: parent.bottom // 将底部的锚点定位到父元素的底部
anchors.bottomMargin: 20 // 设置底部边距为20像素
text: "重置" // 按钮的文本
// 按键点击时触发
onClicked: {
windowId.count = 0 // 重置计数
}
}
// 定义一个定时器
Timer{
id: timerId // 定时器id
interval: 100 // 定义定时器间隔
running: false // 定时器默认不运行
repeat: true // 定时器是否可以重复触发
// 当定时器触发时执行
onTriggered: {
windowId.count = windowId.count + 1 // 计算新的计数值
if (windowId.count >= 100) {
timerId.stop() // 如果进度值超过最大值,停止定时器
startButtonId.text = "开始加载" // 重置开始按钮的文本
}
}
}
}

浙公网安备 33010602011771号