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

相关推荐
水煎包V:YEDIYYDS8889 天前
QT QML 实现的旋钮按钮,类似收音机音量旋钮,可指示方向和角度
qt·qml·旋钮组件
水煎包V:YEDIYYDS88813 天前
QT 在 QML中 嵌入显示qwidget界面显示的两种方式,已在项目中验证
qt·qml·qt开发·qwidget
水煎包V:YEDIYYDS88814 天前
QT QML 实现的摇杆按钮,类似王者荣耀 左边方向导航键
qt·qml·摇杆按钮·导航键
千疑千寻~20 天前
【QML】C++访问QML控件
c++·qml
Wallace Zhang21 天前
PySide6 + QML - Charts07 - 使用checkbox选择需要显示的曲线
vscode·pyside6·qml
Wallace Zhang1 个月前
PySide6 + QML - 调试日志01 -告别打印log中文乱码,快速且简单地解决
qt·pyside6·qml
江公望1 个月前
Qt QHostInfo::lookupHost()函数,10分钟讲清楚
开发语言·qt·qml
江公望1 个月前
Qt告警clazy-detaching-temporary浅谈
qt·qml
Hi202402172 个月前
为QML程序添加启动Logo:提升用户体验
windows·qt·ui·人机交互·qml·启动logo