与python函数的简单按钮单击连接

问题描述 投票:1回答:1

我有一个非常简单的Qml / Python应用程序,在StackView()中包含一些内容,第一页包含一个简单的按钮。我的问题是,Qml和Python之间的一切仅通过信号运行吗?还是可以直接从python脚本中单击按钮触发/调用函数?

没有尝试太多,因为我不确定如何从这里开始

main.qml

import QtQuick 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.5
import "custom/components"


ApplicationWindow {
    visible: true
    width: 800
    height: 600
    minimumWidth: 800
    minimumHeight: 600

    title: qsTr('Primer')

    property bool authorized: false

    signal change_page(bool change)


    // Main Container - View
    StackView {
        id: view
        anchors.fill: parent
        initialItem: home
    }


    // Page Content
    Component {
        id: home
        Page {
            title: qsTr('Home')

            GenButton {
                text: "To Orders"
                bg_color: "white"
                txt_color: "grey"

                onClicked: homeFunc.changePage()
            }
        }
    }

    Component {
        id: orders
        Page {
            title: qsTr('Orders')
        }
    }

    Component {
        id: quotes
        Page {
            title: qsTr('Quotes')
        }
    }

}

GenButton.qml

import QtQuick 2.12
import QtQuick.Controls 2.5


Button {
    id: ctrl

    property color bg_color: "white"
    property color txt_color: "black"

    background: Rectangle {
        color: ctrl.pressed ? Qt.darker(bg_color, 1.25) : bg_color
    }

    contentItem: Text {
        text: ctrl.text
        padding: ctrl.padding
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
        font.family: "Segoe UI"
        font.pixelSize: 14
        color: txt_color
    }
}

main.py

import sys
from PyQt5.QtGui import QGuiApplication, QIcon
from PyQt5.QtQml import QQmlApplicationEngine
from resources.functions.homeFunctions import HomeFunctions


APP = QGuiApplication(sys.argv)
APP.setWindowIcon(QIcon('resources/img/primerLogo.png'))

home_func = HomeFunctions()

ENGINE = QQmlApplicationEngine()
ENGINE.rootContext().setContextProperty('homeFunc', home_func)
ENGINE.load('resources/qml/main.qml')
ENGINE.quit.connect(APP.quit)

sys.exit(APP.exec_())

homeFunctions.py

from PyQt5.QtCore import QObject


class HomeFunctions(QObject):
    def __init__(self):
        QObject.__init__(self)


    def changePage(self):
        print("Button was pressed")

预期结果将是终端打印消息“按钮被按下”,这是一个非常简单的示例,可能已经通过1000种其他方式实现了,但这仅仅是一个测试]]

收到的错误如下:

file:///D:/Personal Backups/CodingProjects/PycharmProjects/calico/resources/qml/main.qml:40: TypeError: Property 'changePage' of object HomeFunctions(0xc3f5c8) is not a function

我有一个非常简单的Qml / Python应用程序,在StackView()中包含一些内容,第一页包含一个简单的按钮。我的问题是,Qml和Python之间的所有内容都可以通过信号运行吗...

python python-3.x pyqt qml pyqt5
1个回答
0
投票

说明:

© www.soinside.com 2019 - 2024. All rights reserved.