qml学习1(基础的控件应用)

1、首先qml是类似于QWidget的一个控制ui界面的文件,其中也有一些控件,不过不想QWidget一样能手动拖动,需要手写
每创建一个qml文件就会有一个窗口部件,你可以向这个窗口中加按钮、文本框等部件
要提醒的一点就是,每句后不用;来结束了
2、每个部件都有其固定的标签id,你如果要访问它就需要通过id访问
但是每个控件的id只能在当前qml文件使用,如果你想要在其他qml文件访问这个控件,就需要在当前要调用的这个控件的qml文件中定义别名
比如是Component1.qml文件中通过property定义,其中别名的名字为textContent

点击查看代码
import QtQuick

Rectangle
{
    width: 50
    height: 50
    color: "Red"
    Text {
        id: name
        text: qsTr("text")
    }
    property alias textContent: name.text
}

然后在其他的qml中使用,就可以这样
点击查看代码
Component1
   {
       id:compt1
       x:100
       y:100
       textContent:"抓到你了"
   }
3、qml文件中不只是单纯的控件,也需要定义一些其他的变量,比如字符串和int类型,也是和上面一样用property关键字定义
点击查看代码
 //自定义的变量
    property string name:"次数"
    property int number: 0
4、除了基本的控件和变量以外,qml还支持类似于信号与槽的操作 比如按钮的点击,你就可以写一个点击操作,在操作中实现字体变化,颜色变化,内容变化等
点击查看代码
onClicked:
        {
            number++
            name="点击了"+number+"次"
            text.font.pixelSize+=5
            compt1.textContent="其他控件改变"
        }
整体的代码:
点击查看代码
import QtQuick
import QtQuick.Controls
Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")
    //自定义的变量
    property string name:"次数"
    property int number: 0
    //控件,在不同的控件中可以相互修改属性(比如标签,位置等自定义属性)
    Text {
        id: text//id是唯一的,也是其他的控件访问这个部件的唯一标识,但只能在同一个qml文件中使用
        text: qsTr(name)
        font.pixelSize: 48
        anchors.centerIn: parent//居中
        color:"blue"
    }
    Button
    {
        id:clicked
        text: qsTr("please click me")
        font.pixelSize: 20
        y:text.y+text.height+10//y的坐标
        anchors.horizontalCenter: parent.horizontalCenter//居中
        //点击后的槽函数,name改了,Text的标签内容就会改变
        onClicked:
        {
            number++
            name="点击了"+number+"次"
            text.font.pixelSize+=5
            compt1.textContent="其他控件改变"
        }
    }
    //使用其他qml文件中的控件
   Component1
   {
       id:compt1
       x:100
       y:100
       textContent:"抓到你了"
   }
}
<details>

posted on 2026-06-27 11:09  dd_l  阅读(4)  评论(0)    收藏  举报