python - 使用 python 中的 PyQt5 按下按钮时更改 QML 中的标签

标签 python qt pyqt qml pyqt5

我正在尝试使用 PyQt5 和 QML 执行一项简单的任务:有一个按钮,单击该按钮即可更改标签。我已经能够在按下按钮时执行 python 函数,但我不知道如何更改标签中的文本。

这是一个最小的例子:

ma​​in.py

from PyQt5.QtWidgets import *
from PyQt5.QtQml import *
from PyQt5.QtCore import *

import sys

def onClicked():
    print('handler called')

if __name__ == '__main__':
    app = QApplication(sys.argv)

    engine = QQmlApplicationEngine()
    engine.load(QUrl('main.qml'))

    win = engine.rootObjects()[0]
    button = win.findChild(QObject, 'myButton')
    button.messageRequired.connect(onClicked)

    sys.exit(app.exec_())

ma​​in.qml

import QtQuick 2.7
import QtQuick.Controls 2.3
import QtQuick.Window 2.3

ApplicationWindow{
    title: qsTr('Quomodo')
    id: mainWindow
    width:  480
    height: 640
    visible: true

    Column {
        anchors.horizontalCenter: parent.horizontalCenter
        spacing: 8
        padding: 8

        Button {
            signal messageRequired
            objectName: "myButton"
            text: qsTr("Work")
            highlighted: true
            onClicked: messageRequired()
        }

        Label {
            text: qsTr("Time")
            anchors.horizontalCenter: parent.horizontalCenter
        }

    } 
}

例如,如何将标签文本更改为“Next”?

注意:这不是 QML not taking ownership of object received from PyQt slot 的重复项。这个问题是关于 Python 和 QML 之间数据的所有权,并且没有回答这个问题。

最佳答案

尝试一下:

from PyQt5.QtGui  import QGuiApplication
from PyQt5.QtQml  import QQmlApplicationEngine
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, QUrl


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

    # signal sending string
    # necessarily give the name of the argument through arguments=['textLabel']
    # otherwise it will not be possible to pick it up in QML
    textResult = pyqtSignal(str, arguments=['textLabel'])

    @pyqtSlot(str)
    def textLabel(self, arg1):
        # do something with the text and emit a signal
        arg1 = arg1.upper()
        self.textResult.emit(arg1)


if __name__ == "__main__":
    import sys
    app    = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    main   = Main()
    engine.rootContext().setContextProperty("main", main)
    engine.load(QUrl('main.qml'))
    engine.quit.connect(app.quit)
    sys.exit(app.exec_())

main.qml

import QtQuick 2.7
import QtQuick.Controls 2.3
import QtQuick.Window 2.3

ApplicationWindow{
    title: qsTr('Quomodo')
    id: mainWindow
    width:  480
    height: 640
    visible: true

    Column {
        anchors.horizontalCenter: parent.horizontalCenter
        spacing: 8
        padding: 8

        Button {
            objectName: "myButton"
            text: qsTr("Work")
            highlighted: true
            onClicked: {
                // call the slot to process the text
                main.textLabel("Next")
            }
        }

        Label {
            id: textResult
            text: qsTr("Time")
            anchors.horizontalCenter: parent.horizontalCenter
        }
    } 

    // Here we take the result of text processing
    Connections {
        target: main

        // Signal Handler 
        onTextResult: {
            // textLabel - was given through arguments=['textLabel']
            textResult.text = textLabel
        }
    }      
}

enter image description here

关于python - 使用 python 中的 PyQt5 按下按钮时更改 QML 中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50115934/

相关文章:

python - 在 Mac 上的 Python virtualenv 中安装 pygit2/libgit2

python - matplotlib:如何使用标记大小/颜色作为绘图中的额外维度?

python - django - 如何渲染我在网页中随处使用的模板?

c++ - QIODevice::read:设备未打开

python - QTableView 中的搜索/查找功能

python - 如何在猜谜游戏中创建猜测计数器

python - 在 Python 和 Qt 之间共享多播接收器端口

Qt – 如何在 QsqlRelationalTableModel 中添加计算列?

python - 如何在 TextEdit 中使用文本并对其应用更改?就像我的代码看到它并告诉我我可以在 -btn_func- 函数中做什么?

python - 在 PyQt 中实现首选项对话框窗口