Skip to content Skip to sidebar Skip to footer

Several Questions About Qml And Pyside2

I have the following cases, I want to use several Qml: 'welcome.qml', 'create.qml', 'dashboard.qml' in which cases to use QQuickview or QqmlApplicationEngine.? I am using 'QQmlApli

Solution 1:

From what the OP provides, I will point out the following aspects:

  • When should QQmlAplicationEngine or QQuickview be used? is better QQmlAplicationEngine or QQuickview ?

    The use of one or the other depends on the root element of the QML, if the root is Window or ApplicationWindow then you must use QQmlAplicationEngine, if instead it is an Item or its derivatives you can use QQuickView. So for the above one is not better than another. What happens if I load a QML with root Window or ApplicationWindow with QQuickView? Then it will show 2 windows: One will be from the QQuickView and the other from the Window or ApplicationWindow. What if I load a QML with Item with QQmlApplicationEngine? Well you will need to place it inside a Window as indicated by the docs:

    Unlike QQuickView, QQmlApplicationEngine does not automatically create a root window. If you are using visual items from Qt Quick, you will need to place them inside of a Window.

  • Do not access QML elements from python/C++

    QML has its own handling of the variables so you could delete it or create it at any time, there is nothing determined, so accessing these objects can be dangerous since they may not have allocated memory. The right thing is to do the opposite, export a QObject to QML and make connections in QML.


We will apply the above concepts to the code provided by the OP (there are types that I have corrected).

  • First of all, since the roots are ApplicationWindow, then QQmlApplicationEngine should be used.

  • Instead of creating the "change" signal in each element, you can export the backend to QML using setContextProperty and then call the slots directly. To obtain the object using rootObjects() is dangerous since there are qmls that are loaded asynchronously, instead use the objectCreated signal.

main.py

import os

from PyQt5 import QtCore, QtGui, QtQml

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))


classBackend(QtCore.QObject):
    def__init__(self, parent=None):
        super().__init__(parent)

        self._engine = QtQml.QQmlApplicationEngine()
        self._welcome = None
        self._wallet = None
        self.engine.objectCreated.connect(self.on_object_created)
        self.engine.rootContext().setContextProperty("backend", self)

        self.load_welcome()

    @propertydefengine(self):
        return self._engine

    @propertydefwelcome(self):
        return self._welcome

    @propertydefwallet(self):
        return self._wallet

    @staticmethoddefcreate_url(qml):
        return QtCore.QUrl.fromLocalFile(os.path.join(CURRENT_DIR, qml))

    defload_welcome(self):
        self.engine.load(self.create_url("welcome.qml"))

    @QtCore.pyqtSlot(QtCore.QObject, QtCore.QUrl)defon_object_created(self, obj, url):
        if url == self.create_url("welcome.qml"):
            self._welcome = obj
        elif url == self.create_url("wallet.qml"):
            self._wallet = obj

    @QtCore.pyqtSlot()defcreate_wallet(self):
        self.welcome.close()
        self.engine.load(self.create_url("wallet.qml"))

    @QtCore.pyqtSlot()defadd_info(self):
        print("add_info")


if __name__ == "__main__":
    import sys

    app = QtGui.QGuiApplication(sys.argv)
    backend = Backend()

    sys.exit(app.exec_())

welcome.qml

importQtQuick2.14importQtQuick.Controls2.14ApplicationWindow {
    id:rootwidth:650;height:390opacity:1visible:trueminimumHeight:232minimumWidth:226title:"open account"flags:Qt.SplashScreenItem {
        id:elementx:9y:88width:560height:300anchors.horizontalCenter:parent.horizontalCenteranchors.verticalCenter:parent.verticalCenterTimer {
            interval:5000;running:true;repeat:falseonTriggered:backend.create_wallet()
        }
        Image {
            id:imagex:130y:60width:342height:188anchors.verticalCenterOffset:-56anchors.horizontalCenterOffset:0anchors.verticalCenter:parent.verticalCenteranchors.horizontalCenter:parent.horizontalCentersource:"neirons_logo.png"fillMode:Image.PreserveAspectFit
        }

        AnimatedImage {
            id:animatedImagex:236y:200width:100height:100source:"loading.gif"
        }
    }
}

wallet.qml

importQtQuick2.14importQtQuick.Controls2.14importQtQuick.Layouts1.14ApplicationWindow {
    id:rootvisible:truewidth:210;height:210Rectangle {
        id:rectanglex:70y:132width:200height:200color:"#72ded8"anchors.verticalCenterOffset:0anchors.horizontalCenterOffset:0anchors.horizontalCenter:parent.horizontalCenteranchors.verticalCenter:parent.verticalCenterColumnLayout {
            x:60y:73width:109height:128anchors.verticalCenter:parent.verticalCenteranchors.horizontalCenter:parent.horizontalCenterTextInput {
                id:nameAccount1text:qsTr("nameAccount")Layout.fillWidth:trueLayout.alignment:Qt.AlignHCenter|Qt.AlignTopLayout.preferredHeight:20Layout.preferredWidth:80verticalAlignment:Text.AlignVCenterfont.pixelSize:12
            }

            TextInput {
                id:nameAccount2text:qsTr("NameAccount")Layout.fillWidth:trueLayout.alignment:Qt.AlignHCenter|Qt.AlignTopLayout.preferredHeight:20Layout.preferredWidth:80font.pixelSize:12
            }
        }

        Button {
            id:submitNameAccountx:50y:134width:81height:23text:qsTr("Add")font.bold:truefont.pointSize:12anchors.horizontalCenter:parent.horizontalCenteronClicked:backend.add_info()
        }
    }
}

Post a Comment for "Several Questions About Qml And Pyside2"