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

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

相关推荐
尘中远12 小时前
【Qwt 7.0 系列】常用图表类型实战 —— 柱状图、散点图、箱线图与直方图
qt·qwt·工业软件·科学绘图
尘中远12 小时前
【Qwt 7.0 系列】交互功能详解 —— 平移、缩放、坐标轴交互与数据拾取
qt·数据可视化·绘图·qcustomplot·qwt·科学绘图
sycmancia12 小时前
Qt——进程与线程的概念
qt
郝学胜-神的一滴13 小时前
Qt 高级编程 034:深耕QWidget底层内核—彻底吃透无边框窗口设计核心原理
开发语言·c++·qt·程序人生·软件开发·用户界面
满天星830357714 小时前
【Qt】控件(二) (geometry及与frameGeometry的区别)
开发语言·qt
大气的小蜜蜂14 小时前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·qt·sqlite
尘中远14 小时前
【Qwt 7.0 系列】总体架构解析 —— 从单体到三库模块化的演进
qt·matplotlib·绘图·qwt·科学绘图
xcyxiner15 小时前
DicomViewer (编译以及优化)8
qt
旖-旎15 小时前
QT界面优化(6)
开发语言·c++·qt
特立独行的猫a15 小时前
为 HarmonyOS/OpenHarmony 构建第三方库的解决方案(转自Qt官方Blog)
qt·华为·harmonyos·三方库·鸿蒙pc