QML调用另一个QML文件并显示

注意

1.调用的qml文件必须也是根元素为window,否则visible元素会报错。
2.QML的文件第一个字母必须大写
3.要调用的QML文件必须在主QML里实例化

Main.qml文件

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    
    
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")


    Qml1{
    
    	//实例化另一个文件,文件名称第一个要大写
        id:qwe
    }


    Rectangle {
    
    
        width: 320; height: 240
        color: "black"

        Text {
    
    
            id: txt
            text: "打开另一个窗口"
            font.pixelSize: 20
            anchors.centerIn: parent
        }
        MouseArea {
    
    
            id: mouse_area
            anchors.fill: parent  // 有效区域
            onClicked: {
    
    
                qwe.show()	//另一个qml文件显示
            }
        }
    }
}

Qml1.qml

import QtQuick 2.0
import QtQuick.Window 2.2

Window {
    
    
    width: 320; height: 240
    visible: false	//该窗口一开始默认隐藏的
    color: "lightblue"
    
    Text {
    
    
        id: txt
        text: "另一个窗口"
        font.pixelSize: 20
        anchors.centerIn: parent
    }
}

python运行代码

from PyQt5.QtQuick import QQuickView
from PyQt5 import  QtGui, QtWidgets, QtCore
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtQml,QtQuick
import sys

app = QtWidgets.QApplication(sys.argv)
engine = QtQml.QQmlApplicationEngine(QUrl('Main.qml')) # 显示window界面
sys.exit(app.exec_()) 

运行结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/youngdianfeng/article/details/107444117