我有test.qml文件,在PyQt5中使用
self.view = QQuickView()
self.view.setResizeMode(QQuickView.SizeRootObjectToView)
self.view.setSource(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__),'test.qml')))
单击时我有一个按钮,它会覆盖test.qml并再次调用view来读取test.qml文件,但它仍然显示旧的test.qml而不是新的。为什么呢?
是否与QQmlEngine clearComponentCache()
有关代码示例:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QUrl
from PyQt5.QtQuick import QQuickView
import os
class Ui_MainWindow(object):
def add(self):
# call a function in a nother python file that will open test.qml and overwite it
# when i call the test.qml again it will show the old version not the new one
self.view.setSource(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__),'root.qml')))
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(420, 380, 113, 32))
self.pushButton.setObjectName("pushButton")
self.frame = QtWidgets.QFrame(self.centralwidget)
self.frame.setGeometry(QtCore.QRect(170, 50, 551, 311))
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
vbox = QtWidgets.QVBoxLayout(self.frame)
# loading the qml for the first time
self.view = QQuickView()
self.view.setResizeMode(QQuickView.SizeRootObjectToView)
self.view.setSource(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__),'root.qml')))
self.widget = QtWidgets.QWidget.createWindowContainer(self.view)
vbox.addWidget(self.widget)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.pushButton.clicked.connect(self.add)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
答案 0 :(得分:0)
我还没有使用QQuickView,而是更喜欢QQmlApplicationEngine。有了它,我使用了类似于概述here的方法。
我想你可以在你的主窗口类中添加这样的方法:
def reload(self):
self.view.engine().clearComponentCache()
self.view.setSource(
QUrl.fromLocalFile(
os.path.join(os.path.dirname(__file__),'root.qml')))
clearComponentCache()
方法会导致引擎丢弃以前加载的任何QML文档。在下一次加载操作(例如,在您的视图上使用setSource()
)时,引擎将强制从磁盘重新加载文件。