Last active
February 26, 2021 10:37
-
-
Save naoki-mizuno/407232a06448d0fe2176f752a126bfa1 to your computer and use it in GitHub Desktop.
Sample script to use command line arguments in Qt (QML)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from PySide2.QtCore import Slot | |
from PySide2.QtCore import Signal | |
from PySide2.QtCore import QUrl | |
from PySide2.QtCore import QObject | |
from PySide2.QtGui import QGuiApplication | |
from PySide2.QtQml import QQmlApplicationEngine | |
from PySide2.QtQml import qmlRegisterType | |
import os | |
import sys | |
import argparse | |
class Backend(QObject): | |
def __init__(self, parent=None): | |
QObject.__init__(self, parent) | |
@Slot(list) | |
def load_args(self, args): | |
description = "foo" | |
parser = argparse.ArgumentParser( | |
description=description, | |
add_help=False, | |
) | |
parser.add_argument( | |
"--bool", | |
action="store_true", | |
help="some boolean option", | |
) | |
parser.add_argument( | |
"strings", | |
nargs="+", | |
help="some strings", | |
) | |
parsed_args, _ = parser.parse_known_args(args[1:]) | |
print(args) | |
print(parsed_args) | |
def main(): | |
app = QGuiApplication(sys.argv) | |
qmlRegisterType(Backend, "PythonBackendLibrary", 1, 0, "PythonBackend") | |
qml_file = "sample.qml" | |
current_dir = os.path.dirname(os.path.realpath(__file__)) | |
filename = os.path.join(current_dir, qml_file) | |
backend = Backend() | |
engine = QQmlApplicationEngine() | |
win = engine.rootContext() | |
engine.load(QUrl.fromLocalFile(filename)) | |
if not engine.rootObjects(): | |
sys.exit(-1) | |
sys.exit(app.exec_()) | |
if __name__ == "__main__": | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import QtQuick 2.0 | |
import QtQuick.Controls 2.0 | |
import PythonBackendLibrary 1.0 | |
ApplicationWindow { | |
id: root | |
width: 100 | |
height: 100 | |
visible: true | |
title: "Sample Application" | |
PythonBackend { | |
id: backend | |
Component.onCompleted: load_args(Qt.application.arguments) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment