当用户单击test1.qml
中的按钮时,我正在尝试打开test2.qml
文件。
我可以使用qml StackLayout
,也可以通过Static Loading
文件和使用qml Loader
来做到这一点。
// main.qml
Window {
width: 400
height: 400
StackLayout {
id: myStack
anchors.fill: parent
Test1 {}
Test2 {}
}
}
// Test1.qml
Item {
width: 400
height: 400
Button {
text: "Move Test2"
onClicked: {
myStack.currentIndex = 1 // Move to page 2
}
}
}
// Test2.qml
Item {
width: 400
height: 400
Button {
text: "Move Test1"
onClicked: {
myStack.currentIndex = 0 // Move to page 1
}
}
}
但是有没有一种方法可以从另一个QML文件中打开.qml文件,而不需要使用StackLayout或Loader,甚至不需要静态地包含文件和设置可见性?
有没有办法可以使用QT Quick C++ API或者直接从QML加载文件?
发布于 2020-12-03 23:44:22
我想你可能在找这个:https://doc.qt.io/qt-5/qtqml-modules-qmldir.html
让我们来看看他们的示例代码:
//Style.qml with custom singleton type definition
pragma Singleton
import QtQuick 2.0
QtObject {
property int textSize: 20
property color textColor: "green"
}
上面是我们想要导入到其他qml文件中的自定义类型。
// qmldir declaring the singleton type
module CustomStyles
singleton Style 1.0 Style.qml
上面是我们放入qmldir文件中的内容。您必须创建一个单独的模块,然后该模块将具有此qmldir文件。您必须使用QtCreator向导创建一个空文件,并将其命名为qmldir。这是Qt模块的一个特性。在qmldir文件中,您可以说“这是我的模块的名称,它在Style.qml中定义了这个类型”。这就是它所做的一切。您可以在其中定义任意数量的qml类型。
// singleton type in use
import QtQuick 2.0
import CustomStyles 1.0
Text {
font.pixelSize: Style.textSize
color: Style.textColor
text: "Hello World"
}
在这里,我们从CustomStyles模块导入样式,并在需要的地方使用它。
所以这里发生的事情是
TEMPLATE = subdirs
创建包含多个模块的项目。创建
import CustomStyles 1.0
或在项目中使用的任意模块名称因此,不要像c++那样考虑它,在python中#包含一个文件,而是更像在python中导入一个模块,然后可以在该模块中引用任何公共类或函数。
如果您需要更多关于如何创建模块的说明,请随时留言。您需要创建一个模块,因为import语句导入的是模块,而不是单个文件。导入模块可以访问qmldir文件中从该模块导出的所有文件。
发布于 2021-01-30 01:24:33
发布于 2021-03-01 02:27:05
首先,我认为不可能以不同的方式加载QML文件,而不是使用Loader或静态导入。
我能想到的唯一另一种方式是直接使用QML Fiel作为一个简单的组件,当它在项目中处于相同的前缀时。
所以为了解释:如果你有一个简单的项目,所有的QML文件都在同一个前缀中。
当你有了这个结构中的所有文件后,你可以直接在这里动态地使用其他的QMl文件。据我所知,这是唯一有效地做到这一点的方法。
下面是代码: main.qml
import QtQuick 2.15
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.3
Window {
width: 400
height: 400
StackLayout {
id: myStack
anchors.fill: parent
Test1 {}
Test2 {}
}
}
Test1.qml
import QtQuick 2.15
import QtQuick.Controls 2.12
Item {
width: 400
height: 400
Button {
text: "Move Test2"
onClicked: {
myStack.currentIndex = 1 // Move to page 2
}
}
}
Test2.qml
import QtQuick 2.15
import QtQuick.Controls 2.5
Item {
width: 400
height: 400
Button {
text: "Move Test1"
onClicked: {
myStack.currentIndex = 0 // Move to page 1
}
}
}
当我有了你在上图中看到的结构时,这个代码对我来说是有效的。我希望这能对你有所帮助。
https://stackoverflow.com/questions/64971542
复制相似问题