本文整理汇总了Python中PyQt5.QtQml.QQmlComponent.create方法的典型用法代码示例。如果您正苦于以下问题:Python QQmlComponent.create方法的具体用法?Python QQmlComponent.create怎么用?Python QQmlComponent.create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtQml.QQmlComponent
的用法示例。
在下文中一共展示了QQmlComponent.create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init_country_names_from_code
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
def init_country_names_from_code(locale):
'''Init the country description as found in GCompris geography/resource/board/board*.qml'''
'''in the global descriptions hash'''
po = None
try:
po = polib.pofile( gcompris_qt + '/po/gcompris_' + locale + '.po')
except:
print "**ERROR: Failed to load po file %s**" %(gcompris_qt + '/po/gcompris_' + locale + '.po')
print ''
app = QCoreApplication(sys.argv)
engine = QQmlEngine()
component = QQmlComponent(engine)
for qml in glob.glob(gcompris_qt + '/src/activities/geography/resource/board/*.qml'):
component.loadUrl(QUrl(qml))
board = component.create()
levels = board.property('levels')
for level in levels.toVariant():
if level.has_key('soundFile') and level.has_key('toolTipText'):
sound = level['soundFile'].split('/')[-1].replace('$CA', 'ogg')
tooltip = level['toolTipText']
if po:
tooltip = po.find(tooltip).msgstr if po.find(tooltip) else tooltip
descriptions[sound] = tooltip
示例2: createChangelogWindow
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
def createChangelogWindow(self):
path = QUrl.fromLocalFile(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "ChangeLog.qml"))
component = QQmlComponent(Application.getInstance()._engine, path)
self._changelog_context = QQmlContext(Application.getInstance()._engine.rootContext())
self._changelog_context.setContextProperty("manager", self)
self._changelog_window = component.create(self._changelog_context)
示例3: createControlInterface
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
def createControlInterface(self):
if self._control_view is None:
Logger.log("d", "Creating control interface for printer connection")
path = QUrl.fromLocalFile(os.path.join(PluginRegistry.getInstance().getPluginPath("USBPrinting"), "ControlWindow.qml"))
component = QQmlComponent(Application.getInstance()._engine, path)
self._control_context = QQmlContext(Application.getInstance()._engine.rootContext())
self._control_context.setContextProperty("manager", self)
self._control_view = component.create(self._control_context)
示例4: spawnFirmwareInterface
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
def spawnFirmwareInterface(self, serial_port):
if self._firmware_view is None:
path = QUrl.fromLocalFile(os.path.join(PluginRegistry.getInstance().getPluginPath("Doodle3D"), "SettingsWindow.qml"))
component = QQmlComponent(Application.getInstance()._engine, path)
self._firmware_context = QQmlContext(Application.getInstance()._engine.rootContext())
self._firmware_context.setContextProperty("manager", self)
self._firmware_view = component.create(self._firmware_context)
self._firmware_view.show()
示例5: _createConfigUI
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
def _createConfigUI(self):
if self._ui_view is None:
Logger.log("d", "Creating ImageReader config UI")
path = QUrl.fromLocalFile(os.path.join(PluginRegistry.getInstance().getPluginPath("ImageReader"), "ConfigUI.qml"))
component = QQmlComponent(Application.getInstance()._engine, path)
self._ui_context = QQmlContext(Application.getInstance()._engine.rootContext())
self._ui_context.setContextProperty("manager", self)
self._ui_view = component.create(self._ui_context)
self._ui_view.setFlags(self._ui_view.flags() & ~Qt.WindowCloseButtonHint & ~Qt.WindowMinimizeButtonHint & ~Qt.WindowMaximizeButtonHint);
self._disable_size_callbacks = False
示例6: get_geography_on_letter_from_code
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
def get_geography_on_letter_from_code():
'''Return all the countries in geography/resource/board/board-x.json'''
words = set()
app = QCoreApplication(sys.argv)
engine = QQmlEngine()
component = QQmlComponent(engine)
for qml in glob.glob(gcompris_qt + '/src/activities/geography/resource/board/*.qml'):
component.loadUrl(QUrl(qml))
board = component.create()
levels = board.property('levels')
for level in levels.toVariant():
if level.has_key('soundFile') and (not level.has_key('type') or level['type'] != "SHAPE_BACKGROUND"):
sound = level['soundFile'].split('/')[-1].replace('$CA', 'ogg')
words.add(sound)
return words
示例7: main
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
def main():
# Set up correct Ctrl-C behavior.
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QGuiApplication( sys.argv )
engine = QQmlEngine()
engine.addImportPath( path.join( path.dirname( __file__ ), 'ui', 'qml' ) )
core.register_types()
component = QQmlComponent( engine )
component.loadUrl( QUrl( '/home/feoh3/.config/nube/hud.qml' ) )
if component.isError():
print( "\n".join( error.toString() for error in component.errors() ) )
else:
window = component.create()
app.exec_()
示例8: createQmlComponent
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
def createQmlComponent(self, qml_file_path: str, context_properties: Dict[str, "QObject"] = None) -> Optional["QObject"]:
if self._qml_engine is None: # Protect in case the engine was not initialized yet
return None
path = QUrl.fromLocalFile(qml_file_path)
component = QQmlComponent(self._qml_engine, path)
result_context = QQmlContext(self._qml_engine.rootContext()) #type: ignore #MyPy doens't realise that self._qml_engine can't be None here.
if context_properties is not None:
for name, value in context_properties.items():
result_context.setContextProperty(name, value)
result = component.create(result_context)
for err in component.errors():
Logger.log("e", str(err.toString()))
if result is None:
return None
# We need to store the context with the qml object, else the context gets garbage collected and the qml objects
# no longer function correctly/application crashes.
result.attached_context = result_context
return result
示例9: PauseBackend
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
class PauseBackend(QObject, Extension):
def __init__(self, parent = None):
super().__init__(parent = parent)
self._additional_component = None
self._additional_components_view = None
Application.getInstance().engineCreatedSignal.connect(self._createAdditionalComponentsView)
def _createAdditionalComponentsView(self):
Logger.log("d", "Creating additional ui components for Pause Backend plugin.")
path = QUrl.fromLocalFile(os.path.join(PluginRegistry.getInstance().getPluginPath("PauseBackendPlugin"), "PauseBackend.qml"))
self._additional_component = QQmlComponent(Application.getInstance()._engine, path)
# We need access to engine (although technically we can't)
self._additional_components_context = QQmlContext(Application.getInstance()._engine.rootContext())
self._additional_components_context.setContextProperty("manager", self)
self._additional_components_view = self._additional_component.create(self._additional_components_context)
if not self._additional_components_view:
Logger.log("w", "Could not create additional components for Pause Backend plugin.")
return
Application.getInstance().addAdditionalComponent("saveButton", self._additional_components_view.findChild(QObject, "pauseResumeButton"))
@pyqtSlot()
def pauseBackend(self):
backend = Application.getInstance().getBackend()
backend._change_timer.timeout.disconnect(backend.slice)
backend._terminate()
backend.backendStateChange.emit(BackendState.Error)
@pyqtSlot()
def resumeBackend(self):
backend = Application.getInstance().getBackend()
backend._change_timer.timeout.connect(backend.slice)
backend.forceSlice()
示例10: PrinterOutputDevice
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
class PrinterOutputDevice(QObject, OutputDevice):
def __init__(self, device_id, parent = None):
super().__init__(device_id = device_id, parent = parent)
self._container_registry = ContainerRegistry.getInstance()
self._target_bed_temperature = 0
self._bed_temperature = 0
self._num_extruders = 1
self._hotend_temperatures = [0] * self._num_extruders
self._target_hotend_temperatures = [0] * self._num_extruders
self._material_ids = [""] * self._num_extruders
self._hotend_ids = [""] * self._num_extruders
self._progress = 0
self._head_x = 0
self._head_y = 0
self._head_z = 0
self._connection_state = ConnectionState.closed
self._connection_text = ""
self._time_elapsed = 0
self._time_total = 0
self._job_state = ""
self._job_name = ""
self._error_text = ""
self._accepts_commands = True
self._preheat_bed_timeout = 900 # Default time-out for pre-heating the bed, in seconds.
self._preheat_bed_timer = QTimer() # Timer that tracks how long to preheat still.
self._preheat_bed_timer.setSingleShot(True)
self._preheat_bed_timer.timeout.connect(self.cancelPreheatBed)
self._printer_state = ""
self._printer_type = "unknown"
self._camera_active = False
self._monitor_view_qml_path = ""
self._monitor_component = None
self._monitor_item = None
self._qml_context = None
def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None):
raise NotImplementedError("requestWrite needs to be implemented")
## Signals
# Signal to be emitted when bed temp is changed
bedTemperatureChanged = pyqtSignal()
# Signal to be emitted when target bed temp is changed
targetBedTemperatureChanged = pyqtSignal()
# Signal when the progress is changed (usually when this output device is printing / sending lots of data)
progressChanged = pyqtSignal()
# Signal to be emitted when hotend temp is changed
hotendTemperaturesChanged = pyqtSignal()
# Signal to be emitted when target hotend temp is changed
targetHotendTemperaturesChanged = pyqtSignal()
# Signal to be emitted when head position is changed (x,y,z)
headPositionChanged = pyqtSignal()
# Signal to be emitted when either of the material ids is changed
materialIdChanged = pyqtSignal(int, str, arguments = ["index", "id"])
# Signal to be emitted when either of the hotend ids is changed
hotendIdChanged = pyqtSignal(int, str, arguments = ["index", "id"])
# Signal that is emitted every time connection state is changed.
# it also sends it's own device_id (for convenience sake)
connectionStateChanged = pyqtSignal(str)
connectionTextChanged = pyqtSignal()
timeElapsedChanged = pyqtSignal()
timeTotalChanged = pyqtSignal()
jobStateChanged = pyqtSignal()
jobNameChanged = pyqtSignal()
errorTextChanged = pyqtSignal()
acceptsCommandsChanged = pyqtSignal()
printerStateChanged = pyqtSignal()
printerTypeChanged = pyqtSignal()
# Signal to be emitted when some drastic change occurs in the remaining time (not when the time just passes on normally).
preheatBedRemainingTimeChanged = pyqtSignal()
@pyqtProperty(QObject, constant=True)
def monitorItem(self):
# Note that we specifically only check if the monitor component is created.
# It could be that it failed to actually create the qml item! If we check if the item was created, it will try to
# create the item (and fail) every time.
if not self._monitor_component:
self._createMonitorViewFromQML()
#.........这里部分代码省略.........
示例11: QApplication
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
from PyQt5.QtQml import QQmlComponent, QQmlApplicationEngine
from PyQt5.QtQuick import QQuickWindow
from view_model import ViewModel
if __name__ == '__main__':
myApp = QApplication(sys.argv)
engine = QQmlApplicationEngine()
context = engine.rootContext()
engine.addImportPath("/home/bob/Qt/5.11.2/Automotive/sources/qtapplicationmanager/dummyimports/")
# create a view model
view_model = ViewModel()
# bind the view model to the context
context.setContextProperty('view_model', view_model)
component = QQmlComponent(engine)
component.loadUrl(QUrl('mainwindow.qml'))
# some boilerplate to make sure the component is ready before showing
if component.status() != QQmlComponent.Ready:
if component.status() == QQmlComponent.Error:
sys.exit(component.errorString())
root_window: QQuickWindow = component.create()
myApp.exec_()
sys.exit()
示例12: QGuiApplication
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
# -*- coding : utf-8 -*-
from PyQt5.QtCore import QUrl,QCoreApplication
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlEngine,QQmlComponent
import os
import sys
app = QGuiApplication(sys.argv)
engine = QQmlEngine()
component = QQmlComponent(engine)
component.loadUrl(QUrl("main.qml"))
top = component.create()
if top :
top.show()
sys.exit(app.exec_())
示例13: DiscoverUM3Action
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
class DiscoverUM3Action(MachineAction):
def __init__(self):
super().__init__("DiscoverUM3Action", catalog.i18nc("@action", "Connect via Network"))
self._qml_url = "DiscoverUM3Action.qml"
self._network_plugin = None
self.__additional_components_context = None
self.__additional_component = None
self.__additional_components_view = None
Application.getInstance().engineCreatedSignal.connect(self._createAdditionalComponentsView)
self._last_zeroconf_event_time = time.time()
self._zeroconf_change_grace_period = (
0.25
) # Time to wait after a zeroconf service change before allowing a zeroconf reset
printersChanged = pyqtSignal()
@pyqtSlot()
def startDiscovery(self):
if not self._network_plugin:
self._network_plugin = (
Application.getInstance().getOutputDeviceManager().getOutputDevicePlugin("UM3NetworkPrinting")
)
self._network_plugin.printerListChanged.connect(self._onPrinterDiscoveryChanged)
self.printersChanged.emit()
## Re-filters the list of printers.
@pyqtSlot()
def reset(self):
self.printersChanged.emit()
@pyqtSlot()
def restartDiscovery(self):
# Ensure that there is a bit of time after a printer has been discovered.
# This is a work around for an issue with Qt 5.5.1 up to Qt 5.7 which can segfault if we do this too often.
# It's most likely that the QML engine is still creating delegates, where the python side already deleted or
# garbage collected the data.
# Whatever the case, waiting a bit ensures that it doesn't crash.
if time.time() - self._last_zeroconf_event_time > self._zeroconf_change_grace_period:
if not self._network_plugin:
self.startDiscovery()
else:
self._network_plugin.startDiscovery()
@pyqtSlot(str, str)
def removeManualPrinter(self, key, address):
if not self._network_plugin:
return
self._network_plugin.removeManualPrinter(key, address)
@pyqtSlot(str, str)
def setManualPrinter(self, key, address):
if key != "":
# This manual printer replaces a current manual printer
self._network_plugin.removeManualPrinter(key)
if address != "":
self._network_plugin.addManualPrinter(address)
def _onPrinterDiscoveryChanged(self, *args):
self._last_zeroconf_event_time = time.time()
self.printersChanged.emit()
@pyqtProperty("QVariantList", notify=printersChanged)
def foundDevices(self):
if self._network_plugin:
if Application.getInstance().getGlobalContainerStack():
global_printer_type = Application.getInstance().getGlobalContainerStack().getBottom().getId()
else:
global_printer_type = "unknown"
printers = list(self._network_plugin.getPrinters().values())
# TODO; There are still some testing printers that don't have a correct printer type, so don't filter out unkown ones just yet.
printers = [
printer
for printer in printers
if printer.printerType == global_printer_type or printer.printerType == "unknown"
]
printers.sort(key=lambda k: k.name)
return printers
else:
return []
@pyqtSlot(str)
def setKey(self, key):
global_container_stack = Application.getInstance().getGlobalContainerStack()
if global_container_stack:
meta_data = global_container_stack.getMetaData()
if "um_network_key" in meta_data:
global_container_stack.setMetaDataEntry("um_network_key", key)
# Delete old authentication data.
global_container_stack.removeMetaDataEntry("network_authentication_id")
global_container_stack.removeMetaDataEntry("network_authentication_key")
else:
global_container_stack.addMetaDataEntry("um_network_key", key)
#.........这里部分代码省略.........
示例14: QApplication
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
#!/usr/bin/env python3
import sys
from PyQt5.QtCore import pyqtProperty, QObject, QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import qmlRegisterType, QQmlComponent, QQmlEngine
# Create the application instance.
app = QApplication(sys.argv)
# Create a QML engine.
engine = QQmlEngine()
# Create a component factory and load the QML script.
component = QQmlComponent(engine)
component.loadUrl(QUrl('main.qml'))
# get window
window = component.create()
window.show()
app.exec_()
示例15: PostProcessingPlugin
# 需要导入模块: from PyQt5.QtQml import QQmlComponent [as 别名]
# 或者: from PyQt5.QtQml.QQmlComponent import create [as 别名]
#.........这里部分代码省略.........
@pyqtProperty(int, notify = selectedIndexChanged)
def selectedScriptIndex(self):
return self._selected_script_index
@pyqtSlot(int, int)
def moveScript(self, index, new_index):
if new_index < 0 or new_index > len(self._script_list) - 1:
return # nothing needs to be done
else:
# Magical switch code.
self._script_list[new_index], self._script_list[index] = self._script_list[index], self._script_list[new_index]
self.scriptListChanged.emit()
self.selectedIndexChanged.emit() #Ensure that settings are updated
## Remove a script from the active script list by index.
@pyqtSlot(int)
def removeScriptByIndex(self, index):
self._script_list.pop(index)
if len(self._script_list) - 1 < self._selected_script_index:
self._selected_script_index = len(self._script_list) - 1
self.scriptListChanged.emit()
self.selectedIndexChanged.emit() # Ensure that settings are updated
## Load all scripts from provided path.
# This should probably only be done on init.
# \param path Path to check for scripts.
def loadAllScripts(self, path):
scripts = pkgutil.iter_modules(path = [path])
for loader, script_name, ispkg in scripts:
# Iterate over all scripts.
if script_name not in sys.modules:
# Import module
loaded_script = __import__("PostProcessingPlugin.scripts."+ script_name, fromlist = [script_name])
loaded_class = getattr(loaded_script, script_name)
temp_object = loaded_class()
Logger.log("d", "Begin loading of script: %s", script_name)
try:
setting_data = temp_object.getSettingData()
if "name" in setting_data and "key" in setting_data:
self._script_labels[setting_data["key"]] = setting_data["name"]
self._loaded_scripts[setting_data["key"]] = loaded_class
else:
Logger.log("w", "Script %s.py has no name or key", script_name)
self._script_labels[script_name] = script_name
self._loaded_scripts[script_name] = loaded_class
except AttributeError:
Logger.log("e", "Script %s.py is not a recognised script type. Ensure it inherits Script", script_name)
except NotImplementedError:
Logger.log("e", "Script %s.py has no implemented settings", script_name)
self.loadedScriptListChanged.emit()
loadedScriptListChanged = pyqtSignal()
@pyqtProperty("QVariantList", notify = loadedScriptListChanged)
def loadedScriptList(self):
return sorted(list(self._loaded_scripts.keys()))
@pyqtSlot(str, result = str)
def getScriptLabelByKey(self, key):
return self._script_labels[key]
scriptListChanged = pyqtSignal()
@pyqtProperty("QVariantList", notify = scriptListChanged)
def scriptList(self):
script_list = [script.getSettingData()["key"] for script in self._script_list]
return script_list
@pyqtSlot(str)
def addScriptToList(self, key):
Logger.log("d", "Adding script %s to list.", key)
new_script = self._loaded_scripts[key]()
self._script_list.append(new_script)
self.setSelectedScriptIndex(len(self._script_list) - 1)
self.scriptListChanged.emit()
## Creates the view used by show popup. The view is saved because of the fairly aggressive garbage collection.
def _createView(self):
Logger.log("d", "Creating post processing plugin view.")
## Load all scripts in the scripts folder
try:
self.loadAllScripts(os.path.join(PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin"), "scripts"))
except Exception as e:
print("Exception occured", e) # TODO: Debug code (far to general catch. Remove this once done testing)
path = QUrl.fromLocalFile(os.path.join(PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin"), "PostProcessingPlugin.qml"))
self._component = QQmlComponent(Application.getInstance()._engine, path)
# We need access to engine (although technically we can't)
self._context = QQmlContext(Application.getInstance()._engine.rootContext())
self._context.setContextProperty("manager", self)
self._view = self._component.create(self._context)
Logger.log("d", "Post processing view created.")
Application.getInstance().addAdditionalComponent("saveButton", self._view.findChild(QObject, "postProcessingSaveAreaButton"))
## Show the (GUI) popup of the post processing plugin.
def showPopup(self):
if self._view is None:
self._createView()
self._view.show()