当前位置: 首页 > news >正文

QML入门之创建可重用的组件(一)

        我们在日常开发中都会封装一些组件以便于项目内重复利用。QML创建可重用组件一般有两种方法。

  1. 自定义Item
  2. 使用Component创建自定义组件

自定义Item

         以一个自定义按钮举例:

import QtQuick 2.12Rectangle {id: root// 自定义属性property string btnDis: qsTr("button")property string pressedColor: "yellow"property string normalColor: "gray"property int btnw: 80property int btnh: 20signal btnClickedradius: 4width: disStr.width> root.width? disStr.width + 8 : btnwheight: btnhcolor: mouseArea.pressed? pressedColor : normalColorText {id: disStranchors.centerIn: parenttext: btnDis}MouseArea {id: mouseAreaanchors.fill: parentonClicked: root.btnClicked()}
}

         然后再主文件直接使用元素即可:

import QtQuick 2.12
import QtQuick.Window 2.12Window {id:rootvisible: truewidth: 640height: 480title: qsTr("简单窗口")RadiusButton {id: loginBtnanchors.centerIn: parentbtnDis: qsTr("马大爷")btnh: 25pressedColor: "green"onBtnClicked: {console.log(qsTr("按钮点击了"))} }
}

注意:

        如果出现找不到组件,则检查下是否将组件添加到了qrc中,如下图:

        如果并不是在根目录下则需要import相应的文件夹,如下:

         在main.qml中 import "qrc:/ui"即可。

 通常,自定义组件时我们会以一个Item作为根节点,可以防止用户通过基本属性改变我们设计的按钮的属性色。修改之后为:

import QtQuick 2.12
Item {id: root// 自定义属性property string btnDis: qsTr("button")property string pressedColor: "yellow"property string normalColor: "gray"property int btnw: 80property int btnh: 20signal btnClickedwidth: rect.widthheight: rect.heightRectangle {id: rectanchors.fill: parentradius: 4width: disStr.width> rect.width? disStr.width + 8 : btnwheight: btnhcolor: mouseArea.pressed? pressedColor : normalColorText {id: disStranchors.centerIn: parenttext: btnDis}MouseArea {id: mouseAreaanchors.fill: parentonClicked: root.btnClicked()}}
}

其中,disStr.width> rect.width? disStr.width + 8 : btnw 即自适应按钮文字大小。


http://www.mrgr.cn/news/22148.html

相关文章:

  • 828华为云征文|Flexus X实例C#/.Net Core 结合(git代码管理、docker自定义镜像)快速发布部署-让你的项目飞起来~
  • 【微前端记录】微前端qiankun初体验
  • 面试字节视觉大模型算法岗,太难了。。。
  • Linux在桌面上创建软件启动快捷方式
  • systemverilog如何用一行code输出两个队列在可变范围内的对比结果
  • 【大数据算法】一文掌握大数据算法之:空间亚线性算法。
  • vulhub GhostScript 沙箱绕过(CVE-2018-16509)
  • GNU风格代码编译(27)
  • react js 笔记 3
  • 【系统架构设计师】抽象工厂设计模式
  • 【c++进阶[五]】list相关接口介绍及list和vector的对比
  • ISAC: Toward Dual-Functional Wireless Networks for 6G and Beyond【论文阅读笔记】
  • golang fmt.Printf中 %q
  • 创建表时添加约束
  • Mac在Python项目中通过opencv模版匹配定位不到图片
  • Oracle rman 没有0级时1级备份和0级大小一样,可以用来做恢复 resetlogs后也可以
  • MySQL record 03 part
  • Elasticsearch Mapping 详解
  • C++11 智能指针
  • ROS 发行版 jazzy 加载urdf 渲染到 RVIZ2