关于QML和PySide2的几个问题

2024-06-30 13:21:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下几种情况,我想使用几个Qml:“welcome.Qml”、“create.Qml”、“dashboard.Qml”

在哪些情况下使用QQuickview或QqmlApplicationEngine

我使用“QQmlAplicatiobEngine”并使用findChild在对象中搜索以获取信号,并处理逻辑,如果信号完成一个条件,我使用engine.load加载另一个QML

python:

class guiBackend(QObject):

    def __init__(self):
        self.engine = QQmlApplicationEngine()
        self.context = self.engine.rootContext()
        self.context.setContextProperty("main", self.engine)
        self.welcome()

    def welcome(self):
        self.engine.load("welcome.qml")
        self.engine.rootObjects()[0].show()
        ob = self.engine.rootObjects()[0]
        next = ob.findChild(QObject, "timer")
        print(dir(next))
        if  path.exists('data.some'):
            next.change.connect(self.open_account)
        else:
            next.change.connect(self.create_account)
    def create(self):
        self.engine.rootObjects()[0].close()
        self.engine.load("create.qml")
        self.engine.rootObjects()[1].show()
        add = ob.findChild(QObject, "addWallet")
        recovery = ob.findChild(QObject, "recovery")
        add.change.connect(self.add_account)
        recovery.change.connect(self.recovery)
        #self.open_account load dashboard.qml and self.account load form.qml

if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    gui = guiBackend()
    sys.exit(app.exec_())

Qml:

ApplicationWindow {
    id: welcome
    width: 650; height: 390
    opacity: 1
    visible: true
    minimumHeight: 232
    minimumWidth:226
    title: "open account"
    flags: Qt.SplashScreen
    Item {

        id: element
        x: 9
        y: 88
        width: 560
        height: 300
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter
        Timer {
        signal change
        objectName: "timer"
        interval: 5000; running: true; repeat: false
        onTriggered: change()
        }
        Image {
            id: image
            x: 130
            y: 60
            width: 342
            height: 188
            anchors.verticalCenterOffset: -56
            anchors.horizontalCenterOffset: 0
            anchors.verticalCenter: parent.verticalCenter
            anchors.horizontalCenter: parent.horizontalCenter
            source: "neirons_logo.png"
            fillMode: Image.PreserveAspectFit
        }

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

create.qml:

ApplicationWindow {
    id: create
    width: 210; height: 210

    Rectangle {
        id: rectangle
        x: 70
        y: 132
        width: 200
        height: 200
        color: "#72ded8"
        anchors.verticalCenterOffset: 0
        anchors.horizontalCenterOffset: 0
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter

        ColumnLayout {
            x: 60
            y: 73
            width: 109
            height: 128
            anchors.verticalCenter: parent.verticalCenter
            anchors.horizontalCenter: parent.horizontalCenter

            TextInput {
                id: nameAccount
                objectName: textAccount
                text: qsTr("nameAccount")
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter | Qt.AlignTop
                Layout.preferredHeight: 20
                Layout.preferredWidth: 80
                verticalAlignment: Text.AlignVCenter
                font.pixelSize: 12
            }

            TextInput {
                id: nameAccount
                objectName: textAccount
                text: qsTr("Name Account")
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter | Qt.AlignTop
                Layout.preferredHeight: 20
                Layout.preferredWidth: 80
                font.pixelSize: 12
            }
        }

        Button {
            signal addinfo
            id: submitNameAccount
            objectName: submit
            x: 50
            y: 134
            width: 81
            height: 23
            text: qsTr("Add")
            font.bold: true
            font.pointSize: 12
            anchors.horizontalCenter: parent.horizontalCenter
            onClicked: addinfo()
    }


}

最好使用QQuickview或QQMlapplicationEngine


Tags: selfidcreateaccountqmlchangewidthengine
1条回答
网友
1楼 · 发布于 2024-06-30 13:21:55

根据OP提供的内容,我将指出以下几个方面:

  • 什么时候应该使用QQmlAplicationEngineQQuickview?更好的是QQmlAplicationEngine还是QQuickview

    一个或另一个的使用取决于QML的根元素,如果根元素是Window或ApplicationWindow,则必须使用QQMLapplicationEngine,如果它是项或其派生项,则可以使用QQuickView。所以对于上面的一个并不比另一个好。如果使用根窗口加载QML或使用QQuickView加载ApplicationWindow,会发生什么情况?然后它将显示两个窗口:一个来自QQuickView,另一个来自窗口或应用程序窗口。如果我加载一个带有QQML应用程序引擎的项的QML会怎么样?您需要将其放置在一个窗口中,如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.

  • 不要从python/C++访问QML元素

    QML有它自己的变量处理,所以您可以随时删除或创建它,因为并没有任何确定,所以访问这些对象可能是危险的,因为它们可能并没有分配内存。正确的做法是做相反的事情,将QObject导出到QML并在QML中建立连接


我们将把上述概念应用到OP提供的代码中(我已经纠正了一些类型)

  • 首先,因为根是ApplicationWindow,所以应该使用QQmlApplicationEngine

  • 您可以使用setContextProperty将后端导出到QML,然后直接调用插槽,而不是在每个元素中创建“change”信号。使用rootObjects()获取对象是危险的,因为存在异步加载的QML,请改用objectCreated信号

main.py

import os

from PyQt5 import QtCore, QtGui, QtQml

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


class Backend(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()

    @property
    def engine(self):
        return self._engine

    @property
    def welcome(self):
        return self._welcome

    @property
    def wallet(self):
        return self._wallet

    @staticmethod
    def create_url(qml):
        return QtCore.QUrl.fromLocalFile(os.path.join(CURRENT_DIR, qml))

    def load_welcome(self):
        self.engine.load(self.create_url("welcome.qml"))

    @QtCore.pyqtSlot(QtCore.QObject, QtCore.QUrl)
    def on_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()
    def create_wallet(self):
        self.welcome.close()
        self.engine.load(self.create_url("wallet.qml"))

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


if __name__ == "__main__":
    import sys

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

    sys.exit(app.exec_())

欢迎光临。qml

import QtQuick 2.14
import QtQuick.Controls 2.14

ApplicationWindow {
    id: root
    width: 650; height: 390
    opacity: 1
    visible: true
    minimumHeight: 232
    minimumWidth:226
    title: "open account"
    flags: Qt.SplashScreen
    Item {
        id: element
        x: 9
        y: 88
        width: 560
        height: 300
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter
        Timer {
            interval: 5000; running: true; repeat: false
            onTriggered: backend.create_wallet()
        }
        Image {
            id: image
            x: 130
            y: 60
            width: 342
            height: 188
            anchors.verticalCenterOffset: -56
            anchors.horizontalCenterOffset: 0
            anchors.verticalCenter: parent.verticalCenter
            anchors.horizontalCenter: parent.horizontalCenter
            source: "neirons_logo.png"
            fillMode: Image.PreserveAspectFit
        }

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

钱包.qml

import QtQuick 2.14
import QtQuick.Controls 2.14
import QtQuick.Layouts 1.14


ApplicationWindow {
    id: root
    visible: true
    width: 210; height: 210

    Rectangle {
        id: rectangle
        x: 70
        y: 132
        width: 200
        height: 200
        color: "#72ded8"
        anchors.verticalCenterOffset: 0
        anchors.horizontalCenterOffset: 0
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter

        ColumnLayout {
            x: 60
            y: 73
            width: 109
            height: 128
            anchors.verticalCenter: parent.verticalCenter
            anchors.horizontalCenter: parent.horizontalCenter

            TextInput {
                id: nameAccount1
                text: qsTr("nameAccount")
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter | Qt.AlignTop
                Layout.preferredHeight: 20
                Layout.preferredWidth: 80
                verticalAlignment: Text.AlignVCenter
                font.pixelSize: 12
            }

            TextInput {
                id: nameAccount2
                text: qsTr("Name Account")
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter | Qt.AlignTop
                Layout.preferredHeight: 20
                Layout.preferredWidth: 80
                font.pixelSize: 12
            }
        }

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

相关问题 更多 >