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

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

相关推荐
kaixin_learn_qt_ing9 小时前
【银河麒麟下】 安装达梦数据库 + 使用Qt访问达梦数据库
qt
mengzhi啊9 小时前
缓存类CacheDataManager把临时数据存入json。做成插件·
qt·缓存·json
尘客-追梦10 小时前
Day 01:插件化之前,先看清 ABI 这堵墙
开发语言·c++·qt
Quz13 小时前
QML SwipeView:实现一个简单的图片浏览器
qt
Quz13 小时前
QML SwipeView:标签导航 与 Loader 懒加载
qt
神仙别闹17 小时前
基于 QT(C++)开发的地铁换乘系统
数据库·c++·qt
C++ 老炮儿的技术栈20 小时前
西门子 S7 常用存储区(I/Q/M/T/C/DB/PI/PQ)
linux·开发语言·c++·windows·qt·io
j7~1 天前
【Qt】(篇二)《信号与槽:信号和槽的概述,使用、自定义信号和槽、信号与槽的连接方式、信号和槽的其他说明》---详解
qt·信号·qt5·信号与槽··qt creater
Littlehero_1212 天前
QT自定义控件之电气接线图(源码开源)
开发语言·qt
qq762118222 天前
Ubuntu22.04 Qt 调用shell 脚本启动程序,GLFW 初始化失败
qt