2

I have a form in QML with two TextFields. How do I access the value entered in the fields in Python?

I'm using PyQt5.5 and Python3.

import sys
from PyQt5.QtCore import QObject, QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView
from PyQt5.QtQml import QQmlApplicationEngine


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

    engine = QQmlApplicationEngine()
    context = engine.rootContext()
    context.setContextProperty("main", engine)

    engine.load('basic.qml')

    win = engine.rootObjects()[0]
    button = win.findChild(QObject, "myButton")
    def myFunction():
        print("handler called")
        foo = win.findChild(QObject, "login")
        print(dir(foo))
        print(foo.text)
    button.clicked.connect(myFunction)
    win.show()

    sys.exit(myApp.exec_())

basic.qml

import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    width: 250; height: 175

    Column {
        spacing: 20
        TextField {
            objectName: "login"
            placeholderText: qsTr("Login")
            focus: true
        }

        TextField {
            placeholderText: qsTr("Password")
            echoMode: TextInput.Password
        }

        Button {
            signal messageRequired
            objectName: "myButton"
            text: "Login"
            onClicked: messageRequired()
        }
    }
}

Console

Traceback (most recent call last):
  File "working.py", line 25, in myFunction
    print(foo.text)
AttributeError: 'QQuickItem' object has no attribute 'text'
fish: “python working.py” terminated by signal SIGABRT (Abort)

1 Answer 1

5

You need to call the property() method of the object to get the desired property.

In your example, you need to call:

print(foo.property("text"))

rather than print(foo.text)

Note that property() returns None if the property doesn't exists.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.