我最近一直在用QTCreator,我很喜欢自动取款机。不幸的是,我想在Python中使用它,但我遇到了一些问题。我遇到的最大问题是发现我的应用程序上下文的子级返回None。
main.py
import sys
from PyQt5.QtCore import QUrl, QSize, QObject
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView
LOGIN_SCREEN_SIZE = QSize(640, 350)
def main():
application = QGuiApplication(sys.argv)
login_window = QQuickView()
login_window.setSource(QUrl('loginscreen.qml'))
login_window.setMinimumSize(LOGIN_SCREEN_SIZE)
login_window.setMaximumSize(LOGIN_SCREEN_SIZE)
login_window.show()
## vvvv Returns None ##
print(login_window.findChild(QObject, 'white_background'))
# login_window.rootObject().open_main_app.connect(app)
sys.exit(application.exec_())
def app(username, password):
print("YAY")
main_window = QQuickView()
main_window.show()
if __name__ == '__main__':
main()loadingscreen.qml
import QtQuick 2.4
import QtQuick.Controls 1.5
Item {
id: window
x: 0
height: 350
visible: true
transformOrigin: Item.Center
rotation: 0
signal open_main_app(string username, string password)
Rectangle {
id: white_background
x: 0
y: 0
width: 640
height: 350
color: "#ffffff"
border.width: 0
Rectangle {
id: green_background
x: 0
y: 0
width: 640
height: 138
color: "#30945d"
}
Text {
id: login_text
x: 0
y: 0
width: 640
height: 124
color: "#b3d756"
text: qsTr("LOGIN")
styleColor: "#f60000"
style: Text.Normal
font.bold: true
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
font.pixelSize: 112
}
TextField {
id: username_box
x: 149
y: 160
width: 384
height: 30
placeholderText: qsTr("Steve")
}
TextField {
id: password_box
x: 149
y: 215
width: 384
height: 30
echoMode: 2
placeholderText: qsTr("qwerty123")
}
Label {
id: label1
x: 40
y: 166
text: qsTr("Username")
}
Label {
id: label2
x: 40
y: 221
text: qsTr("Password")
}
Button {
id: login_button
x: 548
y: 308
text: qsTr("Go")
onClicked:
{
window.open_main_window(username_box.text, password_box.text)
//Qt.quit() << Only works when launching from C++ file
}
}
}
}我测试过的不只是white_background,它们都不能正常工作。我不明白问题出在哪里。顺便说一句,我准备好的信号也不会发送。我一直想尝试手动连接,但我做不到,因为findChild无法工作。
发布于 2016-09-12 20:28:48
这是因为findChild不通过id查找元素。相反,您应该在qml文件中使用objectName。
将white_background矩形重写为:
Rectangle {
id: white_background
objectName: "white_background"
x: 0
y: 0
width: 640
height: 350
color: "#ffffff"
border.width: 0
...
}发布于 2017-09-27 22:21:54
在试图弄清楚如何从pyqt访问TextInput元素的值时遇到了这个问题。我试着按照伊斯梅尔的建议设置objectName,它起作用了。所以我猜ismael在这点上是对的。
以下是我尝试过的有效方法。
@pyqtSlot(result = str)
def saveEdits(self):
comments = appLabel.findChild(QObject, "commentsTextArea").property("text")
print(comments)
return "save edits success"其中appLabel = QQuickView()和commentsTextArea是TextInput元素的objectName。
https://stackoverflow.com/questions/36273655
复制相似问题