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

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

相关推荐
TNTLWT1 小时前
Qt控件:交互控件
开发语言·qt
溟洵4 小时前
【C++ Qt】布局管理器
开发语言·c++·qt
C++ 老炮儿的技术栈5 小时前
自定义CString类与MFC CString类接口对比
c语言·c++·windows·qt·mfc
20242817李臻7 小时前
20242817-李臻-课下作业:Qt和Sqlite
jvm·qt·sqlite
夜松云10 小时前
Qt信号槽机制与UI设计完全指南:从基础原理到实战应用
开发语言·qt·ui·qt designer·布局管理·参数传递·qt信号槽
mahuifa19 小时前
(7)python开发经验
python·qt·pyside6·开发经验
galaxy_strive20 小时前
qtc++ qdebug日志生成
开发语言·c++·qt
TNTLWT20 小时前
Qt功能区:简介与安装
开发语言·qt
凯雀安全1 天前
printspoofer的RPC调用接口的简单代码
qt·网络协议·rpc
六bring个六1 天前
文件系统交互实现
开发语言·c++·qt·交互