2024-08-01 QML开发小技巧一

本集合文章将长期更新一些qml代码中的技巧和问题

正文

有时候可能会遇到同一个qml文件中有多个相同的代码块,如下:

js 复制代码
    Column {
        spacing: 10
        anchors.leftMargin: 10
        anchors.left: parent.left
        GroupBox {
            title: "GroupBox"
            Layout.fillWidth: true
            Column {
                spacing: 10
                Button {
                    id: _button
                    text: "Open Menu"
                }
                TextField {
                    id: _textField
                    width: 100
                }
                Text {
                    id: _text
                    text: qsTr("text")
                }
            }
        }
        GroupBox {
            title: "GroupBox"
            Layout.fillWidth: true
            Column {
                spacing: 10
                Button {
                    // id: _button
                    text: "Open Menu"
                }
                TextField {
                    // id: _textField
                    width: 100
                }
                Text {
                    // id: _text
                    text: qsTr("text")
                }
            }
        }
    }

这样文件内代码量会大量多,且代码在修改时,也不容易定位代码位置。

可能大家都想到重新编写一个qml文件来实现这个GroupBox 里的内容,这确实是可行的,而且很多时候也是这么用的。可是我们可能只是在这个qml文件内使用这个组件,其它qml文件内都不需要使用,这时可以只在这个qml文件内定义一个组件,代码如下:

javascript 复制代码
    component MyGroupBox: GroupBox {
        title: "GroupBox"
        Layout.fillWidth: true
        property alias button: _button
        property alias textField: _textField
        property alias text: _text
        Column {
            spacing: 10
            Button {
                id: _button
                text: "Open Menu"
            }
            TextField {
                id: _textField
                width: 100
            }
            Text {
                id: _text
                text: qsTr("text")
            }
        }
    }

    Column {
        spacing: 10
        anchors.leftMargin: 10
        anchors.left: parent.left
        MyGroupBox {
            button.onClicked: console.log("----")
            textField.text: "Hello"
            text.text: "Hello"
        }
        MyGroupBox {}
    }

这样不止代码量少,而且可以很方便和编写代码

相关推荐
byxdaz12 小时前
QT中服务使用
开发语言·qt
秋田君20 小时前
QT_网络编程体系
网络·arm开发·qt
Quz21 小时前
QML TextArea 实战(下):大文本加载与性能优化
qt
Quz21 小时前
QML TextArea 实战(中):Markdown 渲染与保持滚动
qt
C++ 老炮儿的技术栈2 天前
基于Qt实现轻量化本地音乐播放器
开发语言·c++·qt·c·播放器·音乐
我不是疯子是傻子2 天前
Qt 实时曲线卡顿优化:从QPainter到OpenGL的3级加速实战
开发语言·qt
秋田君2 天前
QT_XML文件操作
xml·数据库·qt
我不是疯子是傻子2 天前
串口通信数据帧粘包拆包再进化:基于 Qt 的滑动窗口与 CRC 校验实战
开发语言·qt
程序员老陆2 天前
Qt中实现窗口真全屏(覆盖Windows任务栏)
开发语言·windows·qt
CodeKwang2 天前
【三维TSP可视化】1000个点以内的最优路径:最近邻 + 2-opt + 3-opt 组合算法实战(Qt实现)
qt·算法