尝试[初级] QML写一个时钟程序

309 阅读2分钟

image.png

本次使用QT完成QML简单应用程序的开发,该程序默认悬浮在 桌面的顶部,并展示当前时间日期。未来打算集成一个英语单词小弹框功能(暂未完成),效果如下。

image.png

什么是QML

QML是一个基于Javascript的宣告式编程语言,主要目的是编写应用界面,QML可以无缝集成和使用C++扩展。QML可以在无需C++基础的基础上编写用户界面,但是并没有HTML这么强大,但依然是描述性很强的编程方式。

本文使用到的特性

本文主要使用了 如下原生组件

使用了1个QT特性 分别是

  • Qt.FramelessWindowHint 隐藏标题栏
  • Qt.WindowStaysOnTopHint 窗口置于顶层

下面代码使用的编程方式说实话不是很喜欢,而且没有HTML那种标记语言写的清晰,样式代码和事件都混合在一起了,而且层层嵌套,虽然可以抽取成组件... 总的来说能写一个支持任意窗口尺寸的工具还是很好的(electron和tauri在禁用resize属性后在gnome桌面系统中最小只能缩放200*200,在小就不行了)

源代码如下


Window {
    id: window
    width: 300
    height: 30
    x: Constants.width / 2 + 200
    y: 30
    visible: true
    title: "单词记忆软件"
    color: "#00000000"
    flags: Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint

    Rectangle {
        width: 280
        x: 0
        y: 0
        height: parent.height
        anchors.fill: parent
        color: "#000000"
        border.width: 2
        border.color: "#c143ee"
        radius: 15

        Rectangle {
            width: 250
            height: parent.height - 6
            x: 8
            y: 4
            color: "#00000000"
            radius: 15
            Timer {
                interval: 50
                running: true
                repeat: true
                onTriggered: {
                    time.text = Qt.formatDateTime(new Date(), "yyyy年MM月dd日 ")
                    time2.text = Qt.formatDateTime(new Date(), "hh时mm分ss秒")
                }
            }

            Row {
                width: parent.width
                height: parent.height
                anchors.centerIn: parent

                x: 2
                Text {
                    id: jx
                    lineHeight: parent.height
                    color: "#ff9f3e"
                    font.pointSize: 14
                    text: " "
                }
                Text {
                    id: time
                    color: "#ff9f3e"
                    font.pointSize: 14
                    text: "time"
                }
                Text {
                    id: time2
                    color: "#ff9f3e"
                    font.pointSize: 14
                    text: "time"
                }
            }
        }
        Rectangle {
            width: 22
            height: 22
            color: "#c143ee"
            x: 274
            y: 4
            radius: 14
            MouseArea {
                anchors.fill: parent

                onPressed: {
                    cursor: Qt.BlankCursor
                    window.height = window.height === 120 ? 30 : 120
                }
            }
        }
    }
    Rectangle {
        width: 296
        x: 2
        y: 30
        height: 88
        color: "#000000"
        radius: 14
        Text {
            font.pointSize: 30
            color: "#85f9cb"
            text: "英语小弹框"
            font.weight: Font.Bold

            anchors.centerIn: parent
        }
    }
}