【问题标题】:Qml import local Files as qualifier doesn't workQml 导入本地文件作为限定符不起作用
【发布时间】:2017-08-09 09:17:00
【问题描述】:

以下代码是我的问题的说明,我导入并限定为 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!")
}

【问题讨论】:

  • 你想达到什么目的?如果您想将其作为单例,请在 qmldir 文件中声明它。否则创建一个实例。为此,您不需要显式导入它,因为它在您的 qrc 中的同一目录中。 qml 文件不是 js 库。
  • 如何在 qmldir 文件中将其声明为单例? ,我正在尝试从 main.qml 发出信号,并在 EventListner.qml 中接收它

标签: javascript qt import directory qml


【解决方案1】:

如果你想拥有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!")
}

然后你需要一个名为qmldir 的文件在你有EventListener.qml 的目录中,内容如下:

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

注意:如果您使用qrc-resource 系统,您需要确保将qmldir-文件添加到其中。 (右键单击 qml.qrc,添加/添加现有(取决于它是否已经创建))。否则需要使用import语句:
import 'file:/path/to/the/directory(可能需要绝对路径)

【讨论】:

  • 我还有一个问题,如果我想使用多个文件,作为单例,我尝试了它,但它不起作用:/,那我该怎么办?
猜你喜欢
  • 2023-02-26
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
相关资源
最近更新 更多