目标效果:点击粉色按钮后,出现一行“为什么非要点我?”的文字。
 
用组件的方式实现:首先单击项目文件夹01,然后右键弹窗中点击“添加新文件” 。

选择 QML File 文件:

文件名就叫Button,然后把代码写进去。
import QtQuick
// 放在一个 Item 中,可以保护某些属性不被修改
Item {
    id: testButton
    // 创建一个别名将text属性开放出来,这个别名就叫text
    property alias text: t1.text
    //这里开放了一个信号,主代码里才能使用 onClicked
    signal clicked
    Rectangle {
        width: 200; height: 50
        color: "pink"
        x: 100; y: 100
        radius: 15
        Text {
            id: t1
            text: "点我!"
            font.pixelSize: 20
            anchors.centerIn: parent
        }
        MouseArea {
            anchors.fill: parent
            onClicked: {
                testButton.clicked()
            }
        }
    }
} 
主文件代码如下:
import QtQuick
Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("组件(Component)")
    Button {
        text: "别点我!😊"
        onClicked: {
            t1.text = "为什么非要点我?😢"
        }
        // color: "blue" 报错!因为color这个属性并未在另外一个文件中开放
    }
    Text {
        id: t1
        // 这里没有设置text是想点击按钮后凭空冒出来,而不是改变
        font.pixelSize: 20
        x: 150; y: 200
    }
} 
项目结构图如下:


















![【C++入门到精通】智能指针 shared_ptr 简介及C++模拟实现 [ C++入门 ]](https://img-blog.csdnimg.cn/direct/ad0cc2887ce140ed8f11e8276788b498.png#pic_center)
