QML自定义组件放入资源里
组件Hello.qml内容,组件名头字母必须大写,组件名就是文件名
import QtQuick 2.0
import "hello.js" as JSCode;
Rectangle{
id:my;
signal myHello(string str); //定义事件事件首字母必须小写
function hello(){
JSCode.hello();
my.myHello("hhh");
}
}
hello.js代码
var ss=1;
function hello(){
console.log("我是组件函数"+ss);
ss++;
}
main.qml
调用
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 1.4
Window {
id:main;
visible: true;
width: 640;
height: 480;
title: qsTr("Hello World");
Rectangle{
id:myRect;
anchors.fill: parent;
Button{
anchors.centerIn: parent;
id:myBT;
text:"你好1";
iconSource: "qrc:/img/QQ.png";
onClicked: {
//uuu.hello();
aaa.hello();
}
}
Button{
anchors.right:parent.right;
id:myBT2;
text:"你好2";
iconSource: "qrc:/img/QQ.png";
onClicked: {
//uuu.hello();
bbb.hello();
}
}
Hello{
id:aaa;
width: 100;
height: 100;
color:"#00ff00";
onMyHello:{ //事件处理 on+事件首字母大写
console.log(str);
}
}
Hello{
id:bbb;
x:aaa.width+20;
width: 100;
height: 100;
color:"#ff0000";
}
}
Component.onCompleted: {
console.log("QML Window\'s c++ type -",main );
console.log("QML Rectangle\'s c++ type -",myRect );
console.log("QML Button\'s c++ type -",myBT );
}
}