QML编码的一些好的做法

时间:2020-06-17 19:35:25   收藏:0   阅读:65

Qt快速布局要求

Qt本身提供Qt Quick快速布局, 以可视化方式在布局中排列Qt Quick Item. 与anchors不同,Qt Quick Layouts可以根据窗口大小调整其子项的大小以便布局. 需注意以下事项:

提倡做法

不提倡做法

RowLayout {
    id: layout
    anchors.fill: parent
    spacing: 6
    Rectangle {
        color: ‘azure‘
        Layout.fillWidth: true
        Layout.minimumWidth: 50
        Layout.preferredWidth: 100
        Layout.maximumWidth: 300
        Layout.minimumHeight: 150
        Text {
            anchors.centerIn: parent
            text: parent.width + ‘x‘ + parent.height
        }
    }
    Rectangle {
        color: ‘plum‘
        Layout.fillWidth: true
        Layout.minimumWidth: 100
        Layout.preferredWidth: 200
        Layout.preferredHeight: 100
        Text {
            anchors.centerIn: parent
            text: parent.width + ‘x‘ + parent.height
        }
    }
}

注意:Layout和anchors都是占用更多内存和实例化时间的对象. 当简单地绑定到x、y、width和height属性就足够时, 避免使用它们(尤其是在列表和表格委托以及控件的样式中)

类型安全

QML中使用var既简单又方便, 但也有几个缺点需注意:

property var name
property var size
property var optionsMenu
property string name
property int size
property MyMenu optionsMenu

更提倡声明式绑定,而不是命令式赋值

在QML中, 可以使用命令式JavaScript代码执行诸如响应输入事件, 通过网络发送数据等任务. 命令式代码在QML中占有重要地位, 但重要的是要知道何时不使用它

例如, 以下命令赋值:

Rectangle {
    Component.onCompleted: color = "red"
}

有以下缺点:

Rectangle {
    color: "red"
}

DPI可扩展的用户界面

随着显示分辨率的提高,可伸缩的应用程序UI变得越来越重要。实现这一点的方法之一是为不同的屏幕分辨率维护UI的几个副本,并根据可用的分辨率加载适当的副本。尽管这工作得很好,但它增加了维护开销。

Qt为这个问题提供了更好的解决方案,建议采用:

有了这些,应用程序的UI就可以根据所提供的显示分辨率进行缩放。

以上文章参考自Qt官方文档: https://doc.qt.io/qt-5/qtquick-bestpractices.html
依个人理解, 简要翻译, 如有错漏, 欢迎指正.

原文:https://www.cnblogs.com/linkyip/p/13153953.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!