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

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

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

自定义Item

以一个自定义按钮举例:

javascript 复制代码
import QtQuick 2.12

Rectangle {
    id: root
    // 自定义属性
    property string btnDis: qsTr("button")
    property string pressedColor: "yellow"
    property string normalColor: "gray"
    property int btnw: 80
    property int btnh: 20
    signal btnClicked
    radius: 4

    width: disStr.width> root.width? disStr.width + 8 : btnw
    height: btnh
    color: mouseArea.pressed? pressedColor : normalColor
    
    Text {
        id: disStr
        anchors.centerIn: parent
        text: btnDis
    }

    MouseArea {
      id: mouseArea
      anchors.fill: parent
      onClicked: root.btnClicked()
    }
}

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

javascript 复制代码
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
  id:root
  visible: true
  width: 640
  height: 480
  title: qsTr("简单窗口")

  RadiusButton {
    id: loginBtn
    anchors.centerIn: parent
    btnDis: qsTr("马大爷")
    btnh: 25
    pressedColor: "green"

    onBtnClicked: {
      console.log(qsTr("按钮点击了"))
    } 
  }
}

注意:

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

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

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

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

javascript 复制代码
import QtQuick 2.12
Item {
  id: root
  // 自定义属性
  property string btnDis: qsTr("button")
  property string pressedColor: "yellow"
  property string normalColor: "gray"
  property int btnw: 80
  property int btnh: 20
  signal btnClicked

  width: rect.width
  height: rect.height

  Rectangle {
    id: rect
    anchors.fill: parent
    radius: 4

    width: disStr.width> rect.width? disStr.width + 8 : btnw
    height: btnh
    color: mouseArea.pressed? pressedColor : normalColor
    
    Text {
        id: disStr
        anchors.centerIn: parent
        text: btnDis
    }

    MouseArea {
      id: mouseArea
      anchors.fill: parent
      onClicked: root.btnClicked()
    }
  }
}

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

相关推荐
大橘3 小时前
【qml-5】qml与c++交互(类型单例)
qt·qml
大橘14 小时前
【qml-4】qml与c++交互(类型多例)
qt·qml
钱彬 (Qian Bin)10 天前
AI质检数据准备利器:基于Qt/QML 5.14的图像批量裁剪工具开发实战
qt·自定义·图像·qml·qt quick·裁剪工具
钱彬 (Qian Bin)21 天前
《使用Qt Quick从零构建AI螺丝瑕疵检测系统》——8. AI赋能(下):在Qt中部署YOLOv8模型
人工智能·qt·yolo·qml·qt quick·工业质检·螺丝瑕疵检测
Little-Hu22 天前
QML 3D曲面图(Surface3D)技术
3d·qml
Little-Hu24 天前
QML视图组件:ListView、GridView、TableView、PathView
数据库·microsoft·qml
钱彬 (Qian Bin)25 天前
《使用Qt Quick从零构建AI螺丝瑕疵检测系统》——6. 传统算法实战:用OpenCV测量螺丝尺寸
教程·cmake·qml·qt quick·工业软件·工业瑕疵检测·qt6.9.1
钱彬 (Qian Bin)1 个月前
《使用Qt Quick从零构建AI螺丝瑕疵检测系统》——4. 前后端联动:打通QML与C++的任督二脉
c++·qt·教程·qml·qt quick·qt 6.9.1·工业瑕疵检测
钱彬 (Qian Bin)1 个月前
《使用Qt Quick从零构建AI螺丝瑕疵检测系统》——0. 博客系列大纲
人工智能·qt·qml·瑕疵检测·qt quick·yolo8·工业质检
丁劲犇1 个月前
Qt Graphs 模块拟取代 charts 和 data visualization还有很长的路要走
c++·qt·qml·visualization·charts·graphs