c++ - QML - 如何将变量从一个 qml 文件发送/传递到另一个 qml 文件

标签 c++ qt qml qt5

如何在 qml 文件之间发送变量或信号?

http://i.stack.imgur.com/MChCG.png

  1. Mainwindow -> 创建组件Item2.qml
  2. MainWindow -> 创建组件 item1.qml
  3. item1.qml -> 创建组件Item3.qml
  4. Item3.qml -> 更改/发送变量或信号到 ItemII.qml(在主窗口中创建)- 如何?

有人可以写一个小例子吗?

最佳答案

示例代码:

Item1.qml

//Item 1
import QtQuick 2.1

Rectangle {
    width: 200
    height: 100
    color:"red"
    Text{
        anchors.centerIn: parent
        font.pixelSize: 16
        text:"Item1"
        width:parent.width
        horizontalAlignment: Text.AlignRight
        color:"white"
    }
}

Item2.qml

//Item 2
import QtQuick 2.1

Rectangle {
    width: 100
    height: 100
    color:"blue"        
    Text{
        anchors.centerIn: parent
        font.pixelSize: 16
        text:"Item2"
        color:"white"
    }
}

Item3.qml

//Item 3
import QtQuick 2.1

Rectangle {
    id:item3
    width: item3Area.pressed?90:100
    height: item3Area.pressed?90:100
    color:"green"
    signal superAwesomeSignal(string txt)
    Text{
        anchors.centerIn: parent
        font.pixelSize: 16
        text:"Item3"
        color:"white"
    }
    MouseArea{
        id:item3Area
        anchors.fill: parent
        onClicked:item3.superAwesomeSignal("Hello, from Item 3 ")
    }
}

主.qml

//Main.qml
import QtQuick 2.0

Rectangle {
    width: 360
    height: 360
    Item1{
        anchors.top: parent.top
        anchors.left: parent.left
        Item3{
            id:item3
            anchors.top: parent.top
            onSuperAwesomeSignal: item2.item3SignalReceived(txt)
        }
    }
    Item2{
        id:item2
        anchors.bottom: parent.bottom
        signal item3SignalReceived(string txt)
        onItem3SignalReceived:console.debug(txt)
    }
}

关于c++ - QML - 如何将变量从一个 qml 文件发送/传递到另一个 qml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22632588/

相关文章:

c++ - 是否有任何 IDE 或插件可以扩展/预处理宏并在不编译的情况下内联显示其结果?

c++ - "::' 变量'"指的是什么?

c++ - std::ostream 到 QDataStream

qt - 如何从 C++ 端多次将 QImage 对象设置为 QML 的 Image 元素?

qt - 如何改变 "Qt Quick - Control 2 RoundButton"的颜色

c++ - std::tuple 成员逐个比较失败

c++ - QVariants 与 QStringList 比较

c++ - 引用 Qt C++ Project 中包含的库

qt - QListWidget 向下滚动列表后拖动

c++ - 将关键事件发送到 Qt QML WebEngineView