如何将信号从一个 qml 发送到另一个 [英] How to send a signal from one qml to another

查看:18
本文介绍了如何将信号从一个 qml 发送到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到从一个 qml 文件与另一个文件通信的方法.我知道有很多方法可以将信号从 qml 发送到 C++ 插槽并反向,但是我所有关于两个不同 qml 文件之间信号的研究都失败了.所以如果有人能告诉我,我必须如何解决这个问题,我会很高兴.

I cannot find a way to communicate from one qml file to the other one. I know there are many ways to send signals from qml to C++ slots and reverse, but all my research about signals between two different qml files failed. So I would be glad if someone can tell me, how I have to solve this problem.

首先是一个抽象的小例子,以便更好地理解问题......

First of all a little abstracted example to understand the problem in a better way...

基础知识中的第一个 QML 如下所示:

The first QML in basics looks like that:

//MyQML1.qml
Rectangle
{    
     id: idMyRec1
     signal mySignalFromQML1()

  Button
  {
       id: idMyButton1
       onClicked:
       {
            idMyRec1.mySignalFromQML1();      //to send the signal
       }
   }
}

第二个是这样的:

//MyQML2.qml
Rectangle
{
    id: idMyRec2

    Text{
         id: idMyText2
         text: "Hello World!"

         onMySignalFromQML1:       //to receive the signal from the other qml
         {                  
             idMyText2.text = "Good Bye World!";
         }
      }
}

所以这个按钮应该将我的第二个 QML 中的文本更改为再见世界!"单击时...但这不起作用...还有其他方法可以将信号从 QML 发送到另一个 QML 吗?!还是我做错了什么?

So this button should change the text in my 2nd QML to "Good Bye World!" when clicked...but this doesn't work...are there any other ways to send signals from QML to another QML?! Or am I doing something wrong?

推荐答案

qml 文件之间不进行通信,QML 文件只是一个原型,对象实例之间进行通信.

You don't communicate between qml files, the QML file is just a prototype, you communicate between the object instances.

  // Rect1.qml
  Rectangle {
    id: rect1
    signal mySignal
    Button {
      onClicked: rect1.mySignal()
    }
  }

  // Rect2.qml
  Rectangle { // Rect1.qml
    property alias text: txt.text
    Text {
      id: txt
    }
  }

然后你创建对象:

Rect1 {
  onMySignal: r2.text = "Goodbye world!"
}

Rect2 {
  id: r2
}

还有其他方法可以建立连接,但是,连接发生在对象实例之间,而不是 qml 文件之间.这些对象也不必在同一个 qml 文件中,但最初对于简单的事情,它们很少会在不同的文件中.

There are other ways to make a connection, however, connections happen between object instances, not qml files. The objects don't have to be in the same qml file too, but initially for simple things they will rarely be in different files.

这篇关于如何将信号从一个 qml 发送到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆