MyComponent.qml
cpp
//import QtQuick 2.0
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
Rectangle{
width: 400
height: 300
property Component com1
property Component com2
border.color: "black"
Loader {
id: loader1
sourceComponent: com1
anchors.bottom: parent.bottom
anchors.bottomMargin: 20
anchors.right: parent.right
anchors.rightMargin: 20
Connections{
target: loader1.item
ignoreUnknownSignals: true
// function onBtnSig(value){
// console.log("right ", value)
// }
function onLeftBtnPressed(){
loader2.item.focus = true
loader2.item.forceActiveFocus()
}
}
Component.onCompleted: {
loader1.item.focus = true
loader1.item.forceActiveFocus()
}
}
Loader {
id: loader2
sourceComponent: com2
anchors.bottom: parent.bottom
anchors.bottomMargin: 20
anchors.right: parent.right
anchors.rightMargin: 150
Connections{
target: loader2.item
ignoreUnknownSignals: true
function onBtnSig(value){
console.log("left ",value)
}
}
}
}
main.qml
cpp
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
Window {
id: window
visible: true
width: 640
height: 480
title: qsTr("Hello World")
color: "white"
Component{
id: com
Button{
id: btn
width: 100
height: 50
background: Rectangle{
anchors.fill: parent
border.color: btn.activeFocus ? "blue" : "black"
}
// signal btnSig(int value)
// onClicked: {
console.log("123")
// btnSig(10)
// }
signal leftBtnPressed()
Keys.onLeftPressed: {
leftBtnPressed()
}
}
}
MyComponent{
com1: com
com2: com
}
// // 信号和槽
// signal testSig(string s, int value)
function func(ss, ii){
console.log(ss,ii)
}
// Button{
// width: 50
// height: 50
// onClicked: {
// testSig("zhangsan","99")
// }
// }
// Connections{
// target: window //发送信号的对象 就是信号从哪里来的
onTestSig: {
console.log(s,value)
}
// function onTestSig(str, ivalue){ //on+信号首字母大写的信号名字
// console.log("hello",str, ivalue)
// }
// }
Component.onCompleted: { //使用connect
testSig.connect(func)
}
}