QML module not found when using qmlRegisterType()
Unsolved
Qt for Python
-
I'm following the QML 6 Book examples for Qt for Python. I'm following the last example using
psutil
but Qt Creator saysQML module not found
when I useqmlRegisterType
to expose a Python class to QML. How can I fix this?Note: the code runs as expected, but I can't switch to QtQuickDesigner in Qt Creator to modify the QML. This is the main reason I want to use Qt Creator, so getting this working is important to me. Can anyone help? Below is the code:
// main.py # This Python file uses the following encoding: utf-8 import psutil import sys from PySide2.QtGui import QGuiApplication from PySide2.QtQml import QQmlApplicationEngine, qmlRegisterType from PySide2.QtCore import Qt, QUrl, QTimer, QAbstractListModel class CpuLoadModel(QAbstractListModel): def __init__(self): QAbstractListModel.__init__(self) self.__cpu_count = psutil.cpu_count() self.__cpu_load = [0] * self.__cpu_count self.__update_timer = QTimer(self) self.__update_timer.setInterval(1000) self.__update_timer.timeout.connect(self.__update) self.__update_timer.start() # The first call returns invalid data psutil.cpu_percent(percpu=True) def __update(self): self.__cpu_load = psutil.cpu_percent(percpu=True) self.dataChanged.emit(self.index(0,0), self.index(self.__cpu_count-1, 0)) def rowCount(self, parent): return self.__cpu_count def data(self, index, role): if (role == Qt.DisplayRole and index.row() >= 0 and index.row() < len(self.__cpu_load) and index.column() == 0): return self.__cpu_load[index.row()] else: return None if __name__ == '__main__': app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() qmlRegisterType(CpuLoadModel, 'PsUtils', 1, 0, 'CpuLoadModel') # this is how i'm exposing the model to QML engine.load(QUrl("main.qml")) if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec_())
// main.qml import QtQuick 2.15 import QtQuick.Window 2.15 import PsUtils 1.0 // this is what's causing the error Window { id: root width: 640 height: 480 visible: true title: qsTr("CPU Load") ListView { anchors.fill: parent model: CpuLoadModel { } delegate: Rectangle { id: delegate required property int display width: parent.width height: 30 color: "white" Rectangle { id: bar width: parent.width * delegate.display / 100.0 height: 30 color: "green" } Text { anchors.verticalCenter: parent.verticalCenter x: Math.min(bar.x + bar.width + 5, parent.width-width) text: delegate.display + "%" } } } }
I'm on Ubuntu 18.04 with the following environment
$ python Python 3.9.4 (default, Apr 9 2021, 01:15:05) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import PySide2 >>> PySide2.__version__ '5.15.2'
Qt Creator info
Qt Creator 4.15.0 Based on Qt 5.15.2 (GCC 7.3.1 20180303 (Red Hat 7.3.1-5), 64 bit) Built on May 4 2021 01:17:20 From revision 978f6caf1e