我在QML中有两个TextFields的表单。如何访问Python中字段中输入的值?
我正在使用PyQt5.5和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_())
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()
}
}
}
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)
答案 0 :(得分:4)
您需要调用对象的property()
方法来获取所需的属性。
在您的示例中,您需要致电:
print(foo.property("text"))
而不是print(foo.text)
请注意,如果属性不存在,property()
会返回None
。