Pyinstaller And Qml Files
Solution 1:
My answer in addition to showing how to use the possible duplicate answer in this particular case, also shows an alternative using Qt's own tools.
1. Copy the .qml to the same executable folder
In this case you have to build the absolute path of the qml using the application path.
import os
import sys
from PySide2 import QtCore, QtGui, QtQml
# https://stackoverflow.com/a/404750/6622587
application_path = (
os.path.dirname(sys.executable)
ifgetattr(sys, "frozen", False)
else os.path.dirname(os.path.abspath(__file__))
)
if __name__ == "__main__":
import os
import sys
app = QtGui.QGuiApplication(sys.argv)
engine = QtQml.QQmlApplicationEngine()
file = os.path.join(application_path, "main.qml")
engine.load(QtCore.QUrl.fromLocalFile(file))
ifnot engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
Then copy the .qml to the same executable folder.
2. Add .qml to as data files
The data files are decompressed in the folder relative to sys._MEIPASS, if the --onefile option is not used then that path is the executable folder otherwise it will be decompressed in the temporary folder.
In your case it implements the following:
├── main.py
└── main.qml
main.py
import os
import sys
from PySide2 import QtCore, QtGui, QtQml
# https://stackoverflow.com/a/42615559/6622587
application_path = (
sys._MEIPASS
ifgetattr(sys, "frozen", False)
else os.path.dirname(os.path.abspath(__file__))
)
if __name__ == "__main__":
import os
import sys
app = QtGui.QGuiApplication(sys.argv)
engine = QtQml.QQmlApplicationEngine()
file = os.path.join(application_path, "main.qml")
engine.load(QtCore.QUrl.fromLocalFile(file))
ifnot engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
And run pyinstaller as follows:
pyinstaller --add-data "main.qml:." --onefile main.py
3. Use Qt Resource
You can create a .qrc that adds the qml, then convert them to .py and finally include it in the .py.
├── main.py
├── main.qml
└── qml.qrc
main.py
import sys
from PySide2 import QtCore, QtGui, QtQml
import qml_rc
if __name__ == "__main__":
import os
import sys
app = QtGui.QGuiApplication(sys.argv)
engine = QtQml.QQmlApplicationEngine()
engine.load(":/main.qml")
ifnot engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
qml.qrc
<RCC><qresourceprefix="/"><file>main.qml</file></qresource></RCC>
To convert the qml.qrc to .py you must use the following command:
pyside2-rcc qml.qrc -o qml_rc.py
and finally as it is already a .py we only run pyinstaller:
pyinstaller main.py--onefile
Post a Comment for "Pyinstaller And Qml Files"