【QML】自定义控件

代码如下:

mian.qml

cpp 复制代码
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15  // 或其他版本
import QtQuick.Layouts 1.15
import QtQuick.Dialogs

//import QtQuick.Dialogs 1.3 // 对于 Qt 5,使用这个导入
import QtQuick.Dialogs 6.3  // 对于 Qt 6,使用:

import "./MyBtn"  //不在同一目录,要导入目录

Window {
    width: 400
    height: 300
    visible: true
    title: "MyButton 示例"

    Row{
        MyButton{
            width: 100
            height: 30
        }

        MyBtn{

        }
    }
}

MyButton.qml

cpp 复制代码
import QtQuick 2.15
import QtQuick.Controls 2.15

Button{
    id:btn
    width: 100
    height: 100
    background: Rectangle{
        width: btn.width    //方便外部修改宽度
        height: btn.height
        color: "blue"
        radius: 10
        MouseArea{
            anchors.fill: parent
            hoverEnabled: true
            onEntered: {
                parent.color = "red"
            }
            onExited: {
                parent.color = "blue"
            }
        }
    }

    onClicked: {
        console.log("点击自定义控件")
    }
}

MyBtn.qml

cpp 复制代码
import QtQuick 2.15
import QtQuick.Controls 2.15

Rectangle{
    width: 100    //方便外部修改宽度
    height: 30
    color: "blue"
    radius: 10
    MouseArea{
        anchors.fill: parent
        hoverEnabled: true
        onEntered: {
            parent.color = "red"
        }
        onExited: {
            parent.color = "blue"
        }
        onClicked: {
            console.log("点击自定义Rectangle控件")
        }
    }
}

同一级的目录一般是可以不用导入的,但是不同级目录是要使用import导入的。

相关推荐
蓝悦无人机11 天前
《地面站软件开发》-第2章ArcGIS Maps SDK for Qt 改变视角
arcgis·上位机·地面站·qml·qt6·qt quick·天地图
Quz17 天前
QML 快捷键篇:基础快捷键与组合键序列
qt·qml
Quz18 天前
QML MouseArea:鼠标拖拽与滚轮缩放
qt·qml
Quz2 个月前
QML 文字入场动画:逐字弹出、逐字飞入、3D 飞入
qt·3d·动画·qml
Quz2 个月前
QML 基础组件专栏目录(V1)
qt·qml
不想学习!!3 个月前
Qt Quick 常用控件入门:Window、Button、CheckBox 与 RadioButton
qt·qml
人还是要有梦想的3 个月前
QT qml布局讲解
qt·布局·qml
Rookie Linux3 个月前
使用Qt6 QML以及第三方库FluentUI、PCapPlusPlus开发一个自定义抓包软件
网络·c++·qt·cmake·qml
谁刺我心3 个月前
[QtCPP]Examples使用示例-QtMultimedia、QMediaPlayer、Audio音频引擎测试mp3播放
qt·音视频·qml
Quz3 个月前
Qt Quick 粒子系统(二):系统控制与生命周期管理
qt·qml·粒子系统