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 {}
    }

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

相关推荐
龚建波11 小时前
《QDebug 2026年6月》
qt
△曉風殘月〆13 小时前
如何在Linux中安装Qt开发环境
linux·运维·qt
Quz18 小时前
QML 选择控件:Switch、CheckBox 与 RadioButton
qt
熬夜苦读学习19 小时前
Qt常用控件
服务器·开发语言·qt
夏玉林的学习之路20 小时前
Qt 项目编译错误排查与解决记录
开发语言·qt
Quz2 天前
QML 基础按钮:Button、RoundButton 与 DelayButton
qt
Quz2 天前
QML ToolTip 组件:图标、多行文本与阴影
qt
xcyxiner2 天前
DicomViewer14(读取图像按固定窗宽窗位显示)
qt
马里马里奥-3 天前
从零搭建AI Agent工具链的技术文章大纲
开发语言·qt
Quz3 天前
QML 与 JavaScript 交互方式:内联函数、外部文件、信号槽与工作线程
javascript·qt