我正在编写一个大型程序,遇到了奇怪的错误。 在 Google 中徘徊,我发现了一个简单的程序,它无法执行预期的功能。
当您按下按钮时,数字应该增加并显示在控制台和字段中。但由于某种原因,该数字仅显示在控制台中。此外,如果在 qml 中将函数调用替换为任意行,则将显示单击后的行。
这就是qml中的界面
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
visible: true
width: 400
height: 200
title: "PySide QML Example"
Rectangle {
anchors.fill: parent
Button {
text: "Increment"
onClicked: {
textField.text = backend.increment_counter().toString();
}
}
TextField {
id: textField
anchors.centerIn: parent
readOnly: true
}
}
}
这是一个简单的程序
import sys
from PySide6.QtCore import Qt, QUrl, Slot, QObject
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
class Backend(QObject):
def __init__(self):
super().__init__()
self.counter = 0
@Slot()
def increment_counter(self):
self.counter += 1
print(self.counter)
return self.counter
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
backend = Backend()
engine = QQmlApplicationEngine()
engine.rootContext().setContextProperty("backend", backend)
qml_file = "main.qml"
engine.load(QUrl.fromLocalFile(qml_file))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec())
我尝试重新安装 pyside 软件包。也许这会有所帮助:在大型程序中,Component.onCompleted 方法对我不起作用,并且不会调用在 qml 中编写的 Python 方法
在上面的示例中,它仅打印增量,因为您错过了 slot() 中的结果。
@Slot(result=int)
def increment_counter(self):
self.counter += 1
print(self.counter)
return self.counter
我不知道这是否能解决你的大程序的问题。但如果我是你,我会专注于每个帖子的一个问题,并发送你收到的完整错误消息。
在这种情况下,例如有一条错误消息:
main.qml:16: TypeError: Cannot call method 'toString' of undefined