我正在尝试运行该网站的最后两个示例,结果两个示例的root = engine.rootObjects()[0] # type: QObject IndexError: list index out of range
错误(根布局的信号连接((其他qml文件的信号连接
如果有帮助的话,我将所有示例文件放在同一目录级别,并将导入语句更改为Pyside6(从Pyside6.QtCore…(,而不是PySide2。我还添加了我的代码版本,如果它更容易查看的话:
main.py:
import sys
from PySide6.QtCore import *
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtWidgets import QApplication
def say(s):
print(s)
if __name__ == '__main__':
app = QApplication()
engine = QQmlApplicationEngine()
engine.load(QUrl.fromLocalFile('main.qml'))
# Get the root object.
root = engine.rootObjects()[0] # type: QObject
# Find the target object. Since our target object is Window, which is the root object. So use it directly.
target_view = root
# Bind signal.
target_view.say.connect(say) # The former one is the signal of qml, and the latter one is from Python
# say() method.
sys.exit(app.exec())
main.qml:
import QtQuick 2.14
import QtQuick.Controls 2.14
import QtQuick.Window 2.12
Window {
visible: true
width: 600; height: 400
signal say(string s)
Button {
text: "hello"
onClicked: say(text)
}
}
错误的可能原因是:
- .qml的路径不正确,因此没有加载.qml
- qml的加载并不像您所假设的那样是同步的
- .qml有一些错误(例如语法(
考虑到上述情况,解决方案为:
import os
import sys
from pathlib import Path
from PySide6.QtCore import QCoreApplication, Qt, QUrl
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtWidgets import QApplication
CURRENT_DIRECTORY = Path(__file__).resolve().parent
def say(s):
print(s)
if __name__ == "__main__":
app = QApplication()
engine = QQmlApplicationEngine()
filename = os.fspath(CURRENT_DIRECTORY / "main.qml")
url = QUrl.fromLocalFile(filename)
def handle_object_created(obj, obj_url):
if obj is None and url == obj_url:
QCoreApplication.exit(-1)
else:
root = engine.rootObjects()[0]
target_view = root
target_view.say.connect(say)
engine.objectCreated.connect(handle_object_created, Qt.QueuedConnection)
engine.load(url)
sys.exit(app.exec())
但无论如何,我不喜欢使用rootObjects,而是导出一个QObject:
import os
import sys
from pathlib import Path
from PySide6.QtCore import QCoreApplication, QObject, Qt, QUrl, Signal
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtWidgets import QApplication
CURRENT_DIRECTORY = Path(__file__).resolve().parent
class Helper(QObject):
say = Signal(str)
def say(s):
print(s)
if __name__ == "__main__":
app = QApplication()
engine = QQmlApplicationEngine()
helper = Helper()
helper.say.connect(say)
engine.rootContext().setContextProperty("helper", helper)
filename = os.fspath(CURRENT_DIRECTORY / "main.qml")
url = QUrl.fromLocalFile(filename)
def handle_object_created(obj, obj_url):
if obj is None and url == obj_url:
QCoreApplication.exit(-1)
engine.objectCreated.connect(handle_object_created, Qt.QueuedConnection)
engine.load(url)
sys.exit(app.exec())
import QtQuick 2.14
import QtQuick.Controls 2.14
import QtQuick.Window 2.12
Window {
visible: true
width: 600
height: 400
Button {
text: "hello"
onClicked: helper.say(text)
}
}