首页 > 解决方案 > 将命令行参数传递给 qml

问题描述

我想从 linux shell 调用一个 qml-script 并传递一个文本作为参数,比如

./message.qml "hello this is a message"

或者

/usr/bin/qt5/qml ./message.qml "hello this is a message"

qml 脚本应该显示该文本。

下面的示例 qml 脚本有效,但显示的文本(“hello”)当然是静态的。是否可以在 qml 中查询命令行参数?

#!/usr/bin/qt5/qml

import QtQuick 2.2


Rectangle {
    width: 1024
    height: 600
    Text {
        anchors.centerIn: parent
        text: "Hello" // here I want to have a text which is set in the call
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit()
        }
    }
}

标签: linuxqtshellqmlcommand-line-arguments

解决方案


您可以使用 访问命令行参数Qt.application.arguments,例如在我的情况下,如果我执行:

/usr/bin/qml message.qml "hello this is a message"
#!/usr/bin/qt5/qml

import QtQuick 2.2


Rectangle {
    width: 1024
    height: 600
    Text {
        anchors.centerIn: parent
        text: Qt.application.arguments[2] // here I want to have a text which is set in the call
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit()
        }
    }
}

中的索引Qt.application.arguments[index]可能会有所不同,具体取决于您调用 qml 执行的方式。


推荐阅读