【QML】

本文介绍了Qt应用程序的基本结构,包括事件循环的实现、控件的使用和布局管理。通过示例展示了如何在QML中创建窗口、设置控件属性、自定义信号和槽函数,以及如何进行事件绑定。此外,还讨论了控件间的通信,强调了避免直接通过id访问,而是通过成员函数和信号槽机制来实现交互。
摘要由CSDN通过智能技术生成

简介

Item内通过id互相访问
使用封装好的控件,通过Item的成员函数访问,不能通过id访问。

事件循环
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickStyle>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QQuickStyle::setStyle(QStringLiteral("qrc:/qml/Style"));
    engine.load(QUrl(QStringLiteral("qrc:/Main.qml")));//加载根窗口
    return app.exec();//渲染和监听事件
}
根窗口
import QtQuick.Window 2.2
Window {
    id: root
    visible: true
    width: 320
    height: 320
}
父子关系
Window {
    id: root
    visible: true
    width: 320
    height: 320
    Button{
        id: button
        anchors.right: parent.right
        text: qsTr("button")
    }
}
生命周期
Window {
     Component.onCompleted: {//构造函数
         function slotslot(){
             myItem.setText();
         }
         myItem.sendSig.connect(slotslot)
     }
     Component.onDestruction: {//析构函数
         console.log("destruct")
     }    
}
控件
Window {
    id: root
    visible: true
    width: 320
    height: 320

    property int age: 18 //自定义属性
    function say(){  //自定义函数
        console.log("hello")
    }
    signal sendSig() //自定义信号,首字母必须小写
    onSendSig: {//on+sendSig绑定,首字母换成大写
        console.log("this is slot"); 
    }
}
事件绑定
Button{
    id: button
    anchors.right: parent.right
    text: qsTr("button")
    function say(){  //自定义函数
   			console.log("hello")
		}
    onClicked: {//on+信号名,绑定
        console.log("i am button")
    }
    clicked.connect(say)//connect绑定
}
布局

在这里插入图片描述

Rectangle { id: rect1; x: 0; ... }
Rectangle { id: rect2; anchors.left: rect1.right; anchors.right: rect3.left; ... }
Rectangle { id: rect3; x: 150; ... }

在这里插入图片描述

自定义控件
控件通信

控件之间通过id相互访问,可以通过id.<member>的方式访问控件对象成员函数、成员属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值