gpt4 book ai didi

javascript - Qml 导入本地文件作为限定符不起作用

转载 作者:行者123 更新时间:2023-12-03 03:41:49 26 4
gpt4 key购买 nike

以下代码是我的问题的说明,我导入并限定为 EventListner 的 qml 文件以蓝色突出显示,但当我使用它时它不起作用。

main.qml:

import QtQuick 2.7
import QtQuick.Window 2.2
import QtQuick.Controls 2.1
import "/qtrealis/untitled15/EventListner.qml" as EventListner
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Button{
onClicked:EventListner.color="blue";
}

EventListner.qml:

import QtQuick 2.7
import QtQuick.Window 2.2
Item {
property string color: "dark"
onColorChanged: console.log("event received!")
}

illustration

最佳答案

如果您想要 EventListener 的单例实例,您需要添加

pragma Singleton

作为 EventListener.qml 的第一行

pragma Singleton

import QtQuick 2.7
import QtQuick.Window 2.2
Item {
property string color: "dark"
onColorChanged: console.log("event received!")
}

然后,您在 EventListener.qml 所在的目录中需要一个名为 qmldir 的文件,其内容为:

singleton EventListener 1.0 EventListener.qml

最后,您可以通过导入在 main.qml 中使用它:

import QtQuick 2.7
import QtQuick.Window 2.2
import QtQuick.Controls 2.1
import '.' // To import Singletons you need to explicitly import the directory
// that holds the qmldir file
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Button {
onClicked: EventListener.color = "blue";
}
}

有关 qmldir 文件的更多信息可以在文档中找到:http://doc.qt.io/qt-5/qtqml-modules-qmldir.html

Note: If you are using the qrc-resource system you need to make sure that the qmldir-file is added to it. (Right-Click on the qml.qrc, Add/Add Existing (depending on whether it is already created)). Otherwise you need to use the import statement:
import 'file:/path/to/the/directory (Maybe absolute path necessary)

关于javascript - Qml 导入本地文件作为限定符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45586455/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com