【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导入的。

相关推荐
Wallace Zhang7 小时前
PySide6 + QML - Charts07 - 使用checkbox选择需要显示的曲线
vscode·pyside6·qml
Wallace Zhang15 天前
PySide6 + QML - 调试日志01 -告别打印log中文乱码,快速且简单地解决
qt·pyside6·qml
江公望21 天前
Qt QHostInfo::lookupHost()函数,10分钟讲清楚
开发语言·qt·qml
江公望24 天前
Qt告警clazy-detaching-temporary浅谈
qt·qml
Hi202402171 个月前
为QML程序添加启动Logo:提升用户体验
windows·qt·ui·人机交互·qml·启动logo
紫荆鱼1 个月前
PCL实战项目-软件界面搭建RibbonUI
qt·pcl·用户界面·qml·点云处理
江公望1 个月前
装了新的QtCreator17,没有用Qt5.12自带的QtCreator4,导致QtCreator17无法找到Qt5.12帮助文档
qt·qml
奔跑吧 android1 个月前
【Qt】【1. 版本特性介绍】
qt·cpp·qml
Wallace Zhang1 个月前
PySide6 + QML - 多线程02 - QThread 生命周期与安全退出
vscode·pyside6·qml