def view(self): with self.__view_creation_lock: if self._view is None: component = QQmlComponent(self.dice.qml_engine, self.qml_file, self) if component.status() == QQmlComponent.Error: qDebug("errors loading component: "+str(component.errors())) qDebug(self.qml_file) for error in component.errors(): qDebug(error.description()) return QQuickItem(self) # don't create the view immediately so the properties are available as soon as the view is created view = component.beginCreate(self.dice.qml_context) if view: view.setParentItem(self.dice.main_window) view.setProperty("appWindow", self.dice.app_window) view.setProperty("app", self) view.setProperty("mainWindow", self.dice.main_window) self._view = view component.completeCreate() self.view_changed.emit() else: component.completeCreate() qDebug("no view") view = QQuickItem(self) view.setParentItem(self.dice.main_window) # TODO: send an alert return view return self._view
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_()
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
party = component.create() if party is not None and party.host is not None: print("\"%s\" is having a birthday!" % party.host.name) if isinstance(party.host, Boy): print("He is inviting:") else: print("She is inviting:") for guest in party.guests: attached = qmlAttachedPropertiesObject(BirthdayParty, guest, False) if attached is not None: rsvpDate = attached.property('rsvp') else: rsvpDate = QDate() if rsvpDate.isNull(): print(" \"%s\" RSVP date: Hasn't RSVP'd" % guest.name) else: print(" \"%s\" RSVP date: %s" % (guest.name, rsvpDate.toString())) party.startParty() else: for e in component.errors(): print("Error:", e.toString()); sys.exit(app.exec_())
@host.setter def host(self, host): self._host = host @pyqtProperty(QQmlListProperty) def guests(self): return QQmlListProperty(Person, self, self._guests) app = QCoreApplication(sys.argv) qmlRegisterType(BirthdayParty, "People", 1, 0, "BirthdayParty") qmlRegisterType(Person, "People", 1, 0, "Person") engine = QQmlEngine() component = QQmlComponent(engine) component.setData(QML, QUrl()) party = component.create() if party is not None and party.host is not None: print('"%s" is having a birthday!' % party.host.name) print("They are inviting:") for guest in party.guests: print(' "%s"' % guest.name) else: for e in component.errors(): print("Error:", e.toString())
toolbar = self.addToolBar('Exit') # toolbar.setObjectName('ToolBar') # toolbar.addAction(exitAction) # toolbar.addAction(processUrlAction) self.restoreState() self.show() if __name__ == '__main__': app = QApplication(sys.argv) qmlRegisterType(JiraMain, 'JiraTree', 1, 0, 'MainWindow') engine = QQmlEngine() # Create a component factory and load the QML script. component = QQmlComponent(engine) component.loadUrl(QUrl.fromLocalFile('main.qml')) jm = component.create() [print(e.toString()) for e in component.errors()] engine.rootContext().setContextProperty("mainWindow", jm) if jm is None: print("JM is none") print({e.toString() for e in component.errors()}) # ex = JiraMain(None) print("Run") app.exec() print("Exit") sys.exit()
class DuetRRFOutputDevice(OutputDevice): def __init__(self, name, url, duet_password, http_user, http_password, device_type): self._device_type = device_type if device_type == DeviceType.print: description = catalog.i18nc("@action:button", "Print on {0}").format(name) name_id = name + "-print" priority = 30 elif device_type == DeviceType.simulate: description = catalog.i18nc("@action:button", "Simulate on {0}").format(name) name_id = name + "-simulate" priority = 20 elif device_type == DeviceType.upload: description = catalog.i18nc("@action:button", "Upload to {0}").format(name) name_id = name + "-upload" priority = 10 else: assert False super().__init__(name_id) self.setShortDescription(description) self.setDescription(description) self.setPriority(priority) self._stage = OutputStage.ready self._name = name self._name_id = name_id self._device_type = device_type self._url = url self._duet_password = duet_password self._http_user = http_user self._http_password = http_password Logger.log("d", self._name_id + " | New DuetRRFOutputDevice created") Logger.log("d", self._name_id + " | URL: " + self._url) Logger.log( "d", self._name_id + " | Duet password: "******"set." if self._duet_password else "empty.")) Logger.log( "d", self._name_id + " | HTTP Basic Auth user: "******"set." if self._http_user else "empty.")) Logger.log( "d", self._name_id + " | HTTP Basic Auth password: "******"set." if self._http_password else "empty.")) self._qnam = QtNetwork.QNetworkAccessManager() self._stream = None self._cleanupRequest() if hasattr(self, '_message'): self._message.hide() self._message = None def _timestamp(self): return ("time", datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')) def _send(self, command, query=None, next_stage=None, data=None): enc_query = urllib.parse.urlencode(query or dict()) if enc_query: command += '?' + enc_query self._request = QtNetwork.QNetworkRequest( QUrl(self._url + "rr_" + command)) self._request.setRawHeader(b'User-Agent', b'Cura Plugin DuetRRF') self._request.setRawHeader(b'Accept', b'application/json, text/javascript') self._request.setRawHeader(b'Connection', b'keep-alive') if self._http_user and self._http_password: self._request.setRawHeader( b'Authorization', b'Basic ' + base64.b64encode("{}:{}".format( self._http_user, self._http_password).encode())) if data: self._request.setRawHeader(b'Content-Type', b'application/octet-stream') self._reply = self._qnam.post(self._request, data) self._reply.uploadProgress.connect(self._onUploadProgress) else: self._reply = self._qnam.get(self._request) if next_stage: self._reply.finished.connect(next_stage) self._reply.error.connect(self._onNetworkError) def requestWrite(self, node, fileName=None, *args, **kwargs): if self._stage != OutputStage.ready: raise OutputDeviceError.DeviceBusyError() if fileName: fileName = os.path.splitext(fileName)[0] + '.gcode' else: fileName = "%s.gcode" % Application.getInstance( ).getPrintInformation().jobName self._fileName = fileName path = QUrl.fromLocalFile( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'UploadFilename.qml')) self._component = QQmlComponent(Application.getInstance()._engine, path) Logger.log("d", self._name_id + " | Errors:", self._component.errors()) self._context = QQmlContext( Application.getInstance()._engine.rootContext()) self._context.setContextProperty("manager", self) self._dialog = self._component.create(self._context) self._dialog.textChanged.connect(self.onFilenameChanged) self._dialog.accepted.connect(self.onFilenameAccepted) self._dialog.open() self._dialog.findChild(QObject, "nameField").setProperty( 'text', self._fileName) self._dialog.findChild(QObject, "nameField").select(0, len(self._fileName) - 6) self._dialog.findChild(QObject, "nameField").setProperty('focus', True) def onFilenameChanged(self): fileName = self._dialog.findChild(QObject, "nameField").property('text') self._dialog.setProperty('validName', len(fileName) > 0) def onFilenameAccepted(self): self._fileName = self._dialog.findChild(QObject, "nameField").property('text') if not self._fileName.endswith('.gcode') and '.' not in self._fileName: self._fileName += '.gcode' Logger.log("d", self._name_id + " | Filename set to: " + self._fileName) self._dialog.deleteLater() # create the temp file for the gcode self._stream = StringIO() self._stage = OutputStage.writing self.writeStarted.emit(self) # show a progress message self._message = Message( catalog.i18nc("@info:progress", "Uploading to {}").format(self._name), 0, False, -1) self._message.show() Logger.log("d", self._name_id + " | Loading gcode...") # find the G-code for the active build plate to print version = Application.getInstance().getVersion() Logger.log("d", "Found Cura %s" % version) if version.startswith('3.0') or version.startswith('3.1'): # Cura 3.0 and 3.1 gcode = getattr( Application.getInstance().getController().getScene(), "gcode_list") else: if version.startswith('3.2'): # Cura 3.2 active_build_plate_id = Application.getInstance( ).getBuildPlateModel().activeBuildPlate else: # Cura 3.3 and later active_build_plate_id = Application.getInstance( ).getMultiBuildPlateModel().activeBuildPlate gcode_dict = getattr( Application.getInstance().getController().getScene(), "gcode_dict") gcode = gcode_dict[active_build_plate_id] lines = len(gcode) Logger.log("d", "Found %s lines of gcode." % lines) # send all the gcode to self._stream nextYield = time() + 0.05 i = 0 for line in gcode: i += 1 self._stream.write(line) if time() > nextYield: self._onProgress(i / lines) QCoreApplication.processEvents() nextYield = time() + 0.05 # start Logger.log("d", self._name_id + " | Connecting...") self._send('connect', [("password", self._duet_password), self._timestamp()], self.onConnected) def onConnected(self): if self._stage != OutputStage.writing: return Logger.log("d", self._name_id + " | Deleting file with the same name...") self._send('delete', [("name", "0:/gcodes/" + self._fileName)], self.onBeforeUploadCleanupDone) def onBeforeUploadCleanupDone(self): if self._stage != OutputStage.writing: return Logger.log( "d", self._name_id + " | Reading and discarding possible error message...") self._send('reply', [], self.onUploadReady) def onUploadReady(self): if self._stage != OutputStage.writing: return Logger.log("d", self._name_id + " | Uploading...") self._stream.seek(0) self._postData = QByteArray() self._postData.append(self._stream.getvalue().encode()) self._send('upload', [("name", "0:/gcodes/" + self._fileName), self._timestamp()], self.onUploadDone, self._postData) def onUploadDone(self): if self._stage != OutputStage.writing: return Logger.log("d", self._name_id + " | Upload done") self._stream.close() self.stream = None if self._device_type == DeviceType.simulate: Logger.log("d", self._name_id + " | Simulating...") if self._message: self._message.hide() self._message = Message( catalog.i18nc( "@info:progress", "Simulating print on {}...\nPLEASE CLOSE DWC AND DO NOT INTERACT WITH THE PRINTER!" ).format(self._name), 0, False, -1) self._message.show() self._send('gcode', [("gcode", 'M37 P"0:/gcodes/' + self._fileName + '"')], self.onSimulationPrintStarted) elif self._device_type == DeviceType.print: self.onReadyToPrint() elif self._device_type == DeviceType.upload: self._send('disconnect') if self._message: self._message.hide() text = "Uploaded file {} to {}.".format( os.path.basename(self._fileName), self._name) self._message = Message(catalog.i18nc("@info:status", text), 0, False) self._message.addAction( "open_browser", catalog.i18nc("@action:button", "Open Browser"), "globe", catalog.i18nc("@info:tooltip", "Open browser to DuetWebControl.")) self._message.actionTriggered.connect( self._onMessageActionTriggered) self._message.show() self.writeSuccess.emit(self) self._cleanupRequest() def onReadyToPrint(self): if self._stage != OutputStage.writing: return Logger.log("d", self._name_id + " | Ready to print") self._send('gcode', [("gcode", 'M32 "0:/gcodes/' + self._fileName + '"')], self.onPrintStarted) def onPrintStarted(self): if self._stage != OutputStage.writing: return Logger.log("d", self._name_id + " | Print started") self._send('disconnect') if self._message: self._message.hide() text = "Print started on {} with file {}".format( self._name, self._fileName) self._message = Message(catalog.i18nc("@info:status", text), 0, False) self._message.addAction( "open_browser", catalog.i18nc("@action:button", "Open Browser"), "globe", catalog.i18nc("@info:tooltip", "Open browser to DuetWebControl.")) self._message.actionTriggered.connect(self._onMessageActionTriggered) self._message.show() self.writeSuccess.emit(self) self._cleanupRequest() def onSimulationPrintStarted(self): if self._stage != OutputStage.writing: return Logger.log( "d", self._name_id + " | Simulation print started for file " + self._fileName) self.onCheckStatus() def onCheckStatus(self): if self._stage != OutputStage.writing: return Logger.log("d", self._name_id + " | Checking status...") self._send('status', [("type", "3")], self.onStatusReceived) def onStatusReceived(self): if self._stage != OutputStage.writing: return reply_body = bytes(self._reply.readAll()).decode() Logger.log("d", self._name_id + " | Status received | " + reply_body) status = json.loads(reply_body) if status["status"] in ['P', 'M']: # still simulating # RRF 1.21RC2 and earlier used P while simulating # RRF 1.21RC3 and later uses M while simulating if self._message and "fractionPrinted" in status: self._message.setProgress(float(status["fractionPrinted"])) QTimer.singleShot(5000, self.onCheckStatus) else: Logger.log("d", self._name_id + " | Simulation print finished") self._send('reply', [], self.onReported) def onReported(self): if self._stage != OutputStage.writing: return reply_body = bytes(self._reply.readAll()).decode().strip() Logger.log("d", self._name_id + " | Reported | " + reply_body) if self._message: self._message.hide() text = "Simulation finished on {}:\n\n{}".format( self._name, reply_body) self._message = Message(catalog.i18nc("@info:status", text), 0, False) self._message.addAction( "open_browser", catalog.i18nc("@action:button", "Open Browser"), "globe", catalog.i18nc("@info:tooltip", "Open browser to DuetWebControl.")) self._message.actionTriggered.connect(self._onMessageActionTriggered) self._message.show() self._send('disconnect') self.writeSuccess.emit(self) self._cleanupRequest() def _onProgress(self, progress): if self._message: self._message.setProgress(progress) self.writeProgress.emit(self, progress) def _cleanupRequest(self): self._reply = None self._request = None if self._stream: self._stream.close() self._stream = None self._stage = OutputStage.ready self._fileName = None def _onMessageActionTriggered(self, message, action): if action == "open_browser": QDesktopServices.openUrl(QUrl(self._url)) if self._message: self._message.hide() self._message = None def _onUploadProgress(self, bytesSent, bytesTotal): if bytesTotal > 0: self._onProgress(int(bytesSent * 100 / bytesTotal)) def _onNetworkError(self, errorCode): Logger.log("e", "_onNetworkError: %s", repr(errorCode)) if self._message: self._message.hide() self._message = None if self._reply: errorString = self._reply.errorString() else: errorString = '' message = Message( catalog.i18nc("@info:status", "There was a network error: {} {}").format( errorCode, errorString), 0, False) message.show() self.writeError.emit(self) self._cleanupRequest()
# Load the qml file into the engine engine.addImportPath(str(resolved_path)) engine.load("main/main.qml") if not engine.rootObjects(): sys.exit(-1) # load the components component = QQmlComponent(engine) component.loadUrl(QUrl("components/Class.qml")) line_component = QQmlComponent(engine) line_component.loadUrl(QUrl("components/Edge.qml")) # check for component creation errors for error in component.errors(): print(error.toString()) # check for component creation errors for error in line_component.errors(): print(error.toString()) classes = [] for index, class_name in enumerate(["Person", "Home"]): # create a new instance of the component cclass = component.create() # set the class name property of the component cclass.setProperty("className", class_name) cclass.setX((cclass.width() + 50) * index) cclass.setParentItem(engine.rootObjects()[0].findChild(QQuickItem)) classes.append(cclass)