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

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

相关推荐
开始了码24 分钟前
QT:ItemWidgets模块介绍
开发语言·qt
大笨象、小笨熊2 小时前
Qt Widgets和Qt Quick在开发工控触摸程序的选择
开发语言·qt
Mark Studio8 小时前
QT linux 静态编译问题记录
开发语言·qt
jf加菲猫12 小时前
第1章 认识Qt
开发语言·c++·qt·ui
Wallace Zhang1 天前
QT开发汇总(更新2025.11.12)
qt·pyside6
●VON1 天前
补充说明:Windows 完全可以开发 Qt 鸿蒙应用!(附专属适配方案)
windows·qt·华为·harmonyos·鸿蒙
开始了码1 天前
关于qt运行程序点击几下未响应的原因
开发语言·qt
Kimser1 天前
QT C++ QWebEngine与Web JS之间通信
javascript·c++·qt
QT 小鲜肉1 天前
【QT/C++】Qt样式设置之CSS知识(系统性概括)
linux·开发语言·css·c++·笔记·qt
Main. 241 天前
从0到1学习Qt -- 常见控件QWidget(二)
qt·学习