Пример #1
0
    def do(self):
        try:
            import depthai
            pipeline = depthai.Pipeline()
            rootGraph = self.pyFlowInstance.graphManager.get().findRootGraph()
            device_nodes = list(
                filter(lambda node: isinstance(node, DeviceNode),
                       rootGraph.getNodesList()))
            for node in device_nodes:
                node.build_pipeline(pipeline)
            for node in device_nodes:
                node.build_connections()

            self.found, self.device_info = depthai.XLinkConnection.getFirstDevice(
                depthai.XLinkDeviceState.X_LINK_UNBOOTED)
            if not self.found:
                raise RuntimeError("Device not found")
            self.device = depthai.Device(pipeline, self.device_info, True)
            self.device.startPipeline()

            self.host_nodes = list(
                filter(lambda node: isinstance(node, HostNode),
                       rootGraph.getNodesList()))
            for node in self.host_nodes:
                node.run_node(self.device)

        except Exception as e:
            traceback.print_exc()
            QMessageBox.warning(self.pyFlowInstance, "Warning", str(e))
Пример #2
0
def ask_login(parent=None):
    # type: (Any) -> AccountInfo
    """Ask login with a dialog.
        parent (QWidget, optional): Defaults to None. Parent widget.

    Returns:
        cgtwq.AccountInfo: Account logged in.
    """

    _app = application()
    dialog = QDialog(parent)
    account_input = QLineEdit()
    password_input = QLineEdit()
    _setup_login_dialog(dialog, account_input, password_input)

    while True:
        dialog.exec_()
        if dialog.result() == QDialog.Rejected:
            raise ValueError("Rejected")
        account, password = account_input.text(), password_input.text()
        try:
            return cgtwq.login(account, password)
        except (ValueError, cgtwq.AccountNotFoundError, cgtwq.PasswordError) as ex:
            msg = text_type(ex)
            QMessageBox.critical(parent, "登录失败", msg)
Пример #3
0
    def updateRestShape(self):
        sel = cmds.ls(sl=True)
        if not sel:
            QMessageBox.warning(self.window, "Nothing Selected",
                                "Nothing Selected")
            return
        sel = sel[0]
        mesh = self.system.DCC.mesh

        # TODO, Check vert number and blendshape input connections
        selVerts = cmds.polyEvaluate(sel, vertex=1)
        meshVerts = cmds.polyEvaluate(mesh, vertex=1)

        if selVerts != meshVerts:
            msg = "Selected object {0} has {1} verts\nBase Object has {2} verts".format(
                sel, selVerts, meshVerts)
            QMessageBox.warning(self.window, "Vert Mismatch", msg)
            return

        # TODO Check for live connections
        bs = self.system.DCC.shapeNode
        cnx = cmds.listConnections(bs, plugs=1, destination=0, type='mesh')
        if cnx:
            cnxs = ', '.join([i.split('.')[0] for i in cnx])
            cnxs = textwrap.fill(cnxs)
            msg = "Some shapes have a live input connection:\n{0}\n\nThese shapes will not get the update.\nContinue anyway?".format(
                cnxs)
            btns = QMessageBox.Ok | QMessageBox.Cancel
            bret = QMessageBox.question(self.window, "Live Connections", msg,
                                        btns)
            if not bret & QMessageBox.Ok:
                return

        updateRestShape(mesh, sel)
Пример #4
0
    def do(self):
        try:
            rootGraph = self.pyFlowInstance.graphManager.get().findRootGraph()
            nodes = []
            connections = []
            global_config = {}
            for node in rootGraph.getNodesList():
                if node.name == GlobalPropertiesNode.__name__:
                    global_config["pipeline_version"] = "test"
                    global_config["Leon OS frequency [kHz]"] = get_pin_value(
                        node.inputs.values(), 'leon_os_freq')
                elif not isinstance(node, ExportableNode):
                    continue
                node, node_connections = node.export()
                nodes.append(node)
                connections += node_connections

            export = json.dumps({
                "globalProperties": global_config,
                "nodes": nodes,
                "connections": connections
            })

            outFilePath, filterString = QFileDialog.getSaveFileName(
                filter="Pipeline config (*.json)")
            if outFilePath != "":
                with open(outFilePath, 'w') as f:
                    f.write(export)
            print("saved!")
        except Exception as e:
            QMessageBox.warning(self.pyFlowInstance, "Warning", str(e))
Пример #5
0
 def save(self, *args, **kwargs):
     try:
         data = {
             "name": self.nameEntry.text(),
             "color_count": int(self.colorEntry.text()),
             "mono_count": int(self.monoEntry.text()),
         }
         if self.depthPresent.isChecked():
             data.update({
                 "depth":
                 True,
                 "left_fov_deg":
                 float(self.leftfovEntry.text()),
                 "right_fov_deg":
                 float(self.rightfovEntry.text()),
                 "rgb_fov_deg":
                 float(self.rgbfovEntry.text()),
                 "left_to_right_distance_cm":
                 float(self.lrdistanceEntry.text()),
                 "left_to_rgb_distance_cm":
                 float(self.lrgbdistanceEntry.text()),
             })
         append_to_json(
             data,
             Path(__file__).parent.parent / Path('custom_devices.json'))
         self.close()
         INITIALIZE()
         self.instance.getRegisteredTools(['NodeBoxTool'])[0].refresh()
     except Exception as e:
         QMessageBox.warning(self, "Warning", str(e))
Пример #6
0
    def shortcuts_info(self):
        data = "Ctrl+N - new file\n"
        data += "Ctrl+S - save\n"
        data += "Ctrl+Shift+S - save as\n"
        data += "Ctrl+O - open file\n"

        data += "Ctrl+D - duplicate\n"
        data += "Alt+Drag - duplicate\n"
        data += "Delete - kill selected nodes\n"

        data += "Ctrl+C - copy\n"
        data += "Ctrl+V - paste\n"

        data += "Ctrl+Z - undo\n"
        data += "Ctrl+Y - redo\n"

        data += "Tab - togle node box\n"
        data += "F - frame Selected\n"
        data += "G - frame All\n"
        data += "C - comment selected nodes\n"

        data += "Ctrl+Shift+ArrowLeft - Align left\n"
        data += "Ctrl+Shift+ArrowUp - Align Up\n"
        data += "Ctrl+Shift+ArrowRight - Align right\n"
        data += "Ctrl+Shift+ArrowBottom - Align Bottom\n"

        QMessageBox.information(self, "Shortcuts", data)
Пример #7
0
def generic_warning(message):
    from Qt.QtWidgets import QMessageBox
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Warning)
    msg.setText(message)
    msg.setStandardButtons(QMessageBox.Ok)
    msg.exec_()
    def onExportToPackage(self):
        # check if category is not empty
        if self._rawNode._rawGraph.category == '':
            QMessageBox.information(
                None, "Warning",
                "Category is not set! Please step into compound and type category name."
            )
            return

        packageNames = list(GET_PACKAGES().keys())
        selectedPackageName, accepted = QInputDialog.getItem(None,
                                                             "Select",
                                                             "Select package",
                                                             packageNames,
                                                             editable=False)
        if accepted:
            packagePath = GET_PACKAGE_PATH(selectedPackageName)
            compoundsDir = os.path.join(packagePath, "Compounds")
            if not os.path.isdir(compoundsDir):
                os.mkdir(compoundsDir)
            self.onExport(root=compoundsDir)
            # refresh node box
            app = self.canvasRef().getApp()
            nodeBoxes = app.getRegisteredTools(
                classNameFilters=["NodeBoxTool"])
            for nodeBox in nodeBoxes:
                nodeBox.refresh()
Пример #9
0
def createConnection():
    db = QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(":memory:")
    if not db.open():
        QMessageBox.critical(
            None,
            QObject.tr("Cannot open database"),
            QObject.tr("Unable to establish a database connection.\n"
                       "This example needs SQLite support. Please read "
                       "the Qt SQL driver documentation for information how "
                       "to build it.\n\n"
                       "Click Cancel to exit."),
            QMessageBox.Cancel,
        )
        return False

    query = QSqlQuery()
    query.exec_("create table person (id int primary key, "
                "firstname varchar(20), lastname varchar(20))")
    query.exec_("insert into person values(101, 'Danny', 'Young')")
    query.exec_("insert into person values(102, 'Christine', 'Holand')")
    query.exec_("insert into person values(103, 'Lars', 'Gordon')")
    query.exec_("insert into person values(104, 'Roberto', 'Robitaille')")
    query.exec_("insert into person values(105, 'Maria', 'Papadopoulos')")

    query.exec_("create table items (id int primary key,"
                "imagefile int,"
                "itemtype varchar(20),"
                "description varchar(100))")
    query.exec_("insert into items "
                "values(0, 0, 'Qt',"
                "'Qt is a full development framework with tools designed to "
                "streamline the creation of stunning applications and  "
                "amazing user interfaces for desktop, embedded and mobile "
                "platforms.')")
    query.exec_("insert into items "
                "values(1, 1, 'Qt Quick',"
                "'Qt Quick is a collection of techniques designed to help "
                "developers create intuitive, modern-looking, and fluid "
                "user interfaces using a CSS & JavaScript like language.')")
    query.exec_("insert into items "
                "values(2, 2, 'Qt Creator',"
                "'Qt Creator is a powerful cross-platform integrated "
                "development environment (IDE), including UI design tools "
                "and on-device debugging.')")
    query.exec_("insert into items "
                "values(3, 3, 'Qt Project',"
                "'The Qt Project governs the open source development of Qt, "
                "allowing anyone wanting to contribute to join the effort "
                "through a meritocratic structure of approvers and "
                "maintainers.')")

    query.exec_("create table images (itemid int, file varchar(20))")
    query.exec_("insert into images values(0, 'images/qt-logo.png')")
    query.exec_("insert into images values(1, 'images/qt-quick.png')")
    query.exec_("insert into images values(2, 'images/qt-creator.png')")
    query.exec_("insert into images values(3, 'images/qt-project.png')")

    return True
Пример #10
0
def warning(message):
    """
    Prints a warning message
    :param message: str
    :return:
    """

    QMessageBox.warning(dcc.get_main_window(), 'Warning', message)
Пример #11
0
    def handleAbout(self):
        """
        Displays the About dialog
        """

        about_box = QMessageBox()
        about_box.setText(__doc__)
        about_box.exec_()
Пример #12
0
 def __init__(self, _msg):
     self.msg_box = QMessageBox()
     self.msg_box.setWindowFlags(self.msg_box.windowFlags()
                                 | QtCore.Qt.WindowStaysOnTopHint)
     self.msg_box.setWindowTitle("Warning")
     self.msg_box.setIcon(QMessageBox.Warning)
     self.msg_box.setStandardButtons(QMessageBox.Ok)
     self.msg_box.setText(_msg)
     self.msg_box.exec_()
Пример #13
0
 def __init__(self):
     self.msg_box = QMessageBox()
     self.msg_box.setWindowFlags(self.msg_box.windowFlags()
                                 | QtCore.Qt.WindowStaysOnTopHint)
     self.msg_box.setWindowTitle("Error")
     self.msg_box.setIcon(QMessageBox.Warning)
     self.msg_box.setStandardButtons(QMessageBox.Ok)
     self.msg_box.setText("File selected not valid")
     self.msg_box.exec_()
Пример #14
0
 def __init__(self):
     self.msg_box = QMessageBox()
     self.msg_box.setWindowFlags(self.msg_box.windowFlags()
                                 | QtCore.Qt.WindowStaysOnTopHint)
     self.msg_box.setWindowTitle("Error")
     self.msg_box.setIcon(QMessageBox.Critical)
     self.msg_box.setStandardButtons(QMessageBox.Ok)
     self.msg_box.setText("Select a file !")
     self.msg_box.exec_()
Пример #15
0
    def doExport(pyFlowInstance):

        supportedDataTypes = {
            "IntPin", "FloatPin", "BoolPin", "StringPin", "ExecPin"
        }
        supportedStructures = {PinStructure.Single}

        script = "# -*- coding: utf-8 -*-\n\n"
        script += "# This file was auto-generated by PyFlow exporter '{0} v{1}'\n".format(
            PythonScriptExporter.displayName(),
            str(PythonScriptExporter.version()))
        script += "#\tCreated: {0}\n\n".format(
            PythonScriptExporter.creationDateString())
        script += "EXPORTER_NAME = '{}'\n".format(
            PythonScriptExporter.displayName())
        script += "EXPORTER_VERSION = '{}'\n\n".format(
            str(PythonScriptExporter.version()))

        rootGraph = pyFlowInstance.graphManager.get().findRootGraph()

        if len(rootGraph.getNodesList()) == 0:
            QMessageBox.warning(pyFlowInstance, "Warning",
                                "Nothing to export!")
            return

        try:
            # create root level nodes
            graphScript = ""
            for node in rootGraph.getNodesList():
                graphScript += nodeToScript(node, supportedDataTypes,
                                            supportedStructures)

            graphScript += "\n# connect pins\n"

            # create connections
            # for node in rootGraph.getNodesList():
            #     for outPin in node.outputs.values():
            #         for inPinName in outPin.linkedTo:
            #             inPin = pyFlowInstance.graphManager.get().findPinByName(inPinName)
            #             graphScript += "{0} = ROOT_GRAPH.graphManager.findPinByName('{1}')\n".format(outPin.getFullName(), outPin.getFullName())
            #             graphScript += "{0} = ROOT_GRAPH.graphManager.findPinByName('{1}')\n".format(inPin.getFullName(), inPin.getFullName())
            #             graphScript += "connectPins({0}, {1})\n".format(outPin.getFullName(), inPin.getFullName())

            wrappedGraphScript = wrapStringToFunctionDef(
                "createScene", graphScript, {"ROOT_GRAPH": None})

            script += wrappedGraphScript + "\n"

            outFilePath, filterString = QFileDialog.getSaveFileName(
                filter=PythonScriptExporter.name_filter)
            if outFilePath != "":
                with open(outFilePath, 'w') as f:
                    f.write(script)
            print("saved!")
        except Exception as e:
            QMessageBox.warning(pyFlowInstance, "Warning", str(e))
Пример #16
0
def qMsgBoxWarning(parentWidg, titleMsgBx, messageMsgBx):
    qmsgParent = None
    if(parentWidg is not None):
        qmsgParent = parentWidg
    reply = QMessageBox.Ok
    try:
        reply = QMessageBox.warning(qmsgParent, titleMsgBx, messageMsgBx)
    except:
        parentScreen = QtGui.QApplication.desktop().screen(QtGui.QApplication.desktop().primaryScreen())
        qmsgParent = QtGui.QMainWindow(parentScreen)
        reply = QMessageBox.warning(qmsgParent, titleMsgBx, messageMsgBx)
    return reply
Пример #17
0
def qMsgBoxCritical(parentWidg, titleMsgBx, messageMsgBx, buttonFlagsMsgBxm = QMessageBox.Ok | QMessageBox.Default, defaultBtnMsgBx = QMessageBox.NoButton ):
    qmsgParent = None
    if(parentWidg is not None):
        qmsgParent = parentWidg
    reply = defaultBtnMsgBx
    try:
        reply = QMessageBox.critical(qmsgParent, titleMsgBx, messageMsgBx, buttonFlagsMsgBxm, defaultBtnMsgBx)
    except:
        parentScreen = QtGui.QApplication.desktop().screen(QtGui.QApplication.desktop().primaryScreen())
        qmsgParent = QtGui.QMainWindow(parentScreen)
        reply = QMessageBox.critical(qmsgParent, titleMsgBx, messageMsgBx, buttonFlagsMsgBxm, defaultBtnMsgBx)
    return reply
Пример #18
0
    def show_info_dialog(self, msg, title='Info'):
        """
        Shows a info dialog
        :param msg: str, message to show with the dialog
        :param title: str, title of the dialog
        """

        dialog = QMessageBox()
        dialog.setIcon(QMessageBox.Information)
        dialog.setWindowTitle(title)
        dialog.setText(msg)
        dialog.exec_()
Пример #19
0
    def __init__(self, parent: QWidget = None):
        super().__init__(parent)

        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)

        self.server = QLocalServer(self)

        if not self.server.listen("fortune"):
            QMessageBox.critical(
                self,
                self.tr("Local Fortune Server"),
                self.tr("Unable to start the server: %s." %
                        (self.server.errorString())),
            )
            QTimer.singleShot(0, self.close)
            return

        statusLabel = QLabel()
        statusLabel.setWordWrap(True)
        statusLabel.setText(
            self.
            tr("The server is running.\nRun the Local Fortune Client example now."
               ))

        self.fortunes = (
            self.tr(
                "You've been leading a dog's life. Stay off the furniture."),
            self.tr("You've got to think about tomorrow."),
            self.tr("You will be surprised by a loud noise."),
            self.tr("You will feel hungry again in another hour."),
            self.tr("You might have mail."),
            self.tr("You cannot kill time without injuring eternity."),
            self.tr(
                "Computers are not intelligent. They only think they are."),
        )

        quitButton = QPushButton(self.tr("Quit"))
        quitButton.setAutoDefault(False)
        quitButton.clicked.connect(self.close)
        self.server.newConnection.connect(self.sendFortune)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout(self)
        mainLayout.addWidget(statusLabel)
        mainLayout.addLayout(buttonLayout)

        self.setWindowTitle(QGuiApplication.applicationDisplayName())
Пример #20
0
	def grabDrvPose(self):
		if not self.isBuilt():
			msg = "PSD System hasn't been built"
			QMessageBox.warning(self, "Brigks", msg, QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
			return 
		
		# Set marker transforms to match rig objects
		for item in self.getObject(config.USE_RIG, localName=None):
			part = item.name().split("_")[-1]
			if part not in self.guide().markers().keys():
				continue
			marker = self.guide().markers(part)
			marker.setTransform(item.transform(world=True), world=True, childCompensation=True)
Пример #21
0
	def grabTwistFromRig(self, minMax):
		if not self.isBuilt()::
			msg = "PSD System hasn't been built"
			QMessageBox.warning(self, "Brigks", msg, QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
			return

		axis = "XYZ".index(self.settings("twistAxis"))
		currentValue = cmds.getAttr(self.getAttribute("OutRot"))[axis]
		self.__dict__["uiTwist{}".format(minMax)].setValue(currentValue)

		# set the value back into the rig, if created
		attr = self.getAttribute("Twist{}".format(minMax))
		if attr:
			cmds.setAttr(attr, currentValue)
Пример #22
0
 def save(self):
     if not config.HAVE_PYEVTK:
         msg = QMessageBox(QMessageBox.Critical, 'Error', 'VTK output disabled. Pleas install pyvtk.')
         msg.exec_()
         return
     filename = QFileDialog.getSaveFileName(self, 'Save as vtk file')[0]
     base_name = filename.split('.vtu')[0].split('.vtk')[0].split('.pvd')[0]
     if base_name:
         if len(self.U) == 1:
             write_vtk(self.grid, NumpyVectorSpace.make_array(self.U[0]), base_name, codim=self.codim)
         else:
             for i, u in enumerate(self.U):
                 write_vtk(self.grid, NumpyVectorSpace.make_array(u), f'{base_name}-{i}',
                           codim=self.codim)
Пример #23
0
 def save(self):
     if not config.HAVE_PYVTK:
         msg = QMessageBox(QMessageBox.Critical, 'Error', 'VTK output disabled. Pleas install pyvtk.')
         msg.exec_()
         return
     filename = QFileDialog.getSaveFileName(self, 'Save as vtk file')[0]
     base_name = filename.split('.vtu')[0].split('.vtk')[0].split('.pvd')[0]
     if base_name:
         if len(self.U) == 1:
             write_vtk(self.grid, NumpyVectorSpace.make_array(self.U[0]), base_name, codim=self.codim)
         else:
             for i, u in enumerate(self.U):
                 write_vtk(self.grid, NumpyVectorSpace.make_array(u), '{}-{}'.format(base_name, i),
                           codim=self.codim)
Пример #24
0
    def openFile(self, path: str) -> None:
        f = QFile(path)

        if not f.open(QIODevice.ReadOnly):

            QMessageBox.warning(
                self,
                self.windowTitle(),
                self.tr("Could not open file %s: %s" %
                        (QDir.toNativeSeparators(path), f.errorString())),
            )
            return

        self.m_filePath = path
        self.editor.setPlainText(f.readAll().data().decode())
Пример #25
0
 def submit(self):
     self.model.database().transaction()
     if self.model.submitAll():
         self.model.database().commit()
     else:
         self.model.database().rollback()
         QMessageBox.warning(
             self,
             self.tr("Cached Table"),
             self.tr(
                 "The database reported an error: {}".format(
                     self.model.lastError().text()
                 )
             ),
         )
Пример #26
0
    def show_confirm_dialog(self, msg, title='Title'):
        """
        Shows a yes/no confirmation dialog
        :param msg: str, message to show with the dialog
        :param title: str, title of the dialog
        :return: bool, Whether the user has pressed yes(True) or No(False)
        """

        dialog = QMessageBox()
        dialog.setIcon(QMessageBox.Question)
        result = dialog.question(self.parent_window, title, msg,
                                 QMessageBox.Yes, QMessageBox.No)
        if result == QMessageBox.Yes:
            return True
        return False
Пример #27
0
def main():
    import sys

    app = QApplication(sys.argv)

    input_device = QAudioDeviceInfo.defaultInputDevice()
    if input_device.isNull():
        QMessageBox.warning(None, "audio",
                            "There is no audio input device available.")
        sys.exit(-1)

    w = Widget(input_device)
    w.show()

    sys.exit(app.exec_())
Пример #28
0
def show_error(parent, title, error):
    """
    Show a error QMessageBox with the given error
    :return:
    """

    return QMessageBox.critical(parent, title, error)
Пример #29
0
def show_info(parent, title, info):
    """
    Show a info QMessageBox with the given info
    :return:
    """

    return QMessageBox.information(parent, title, info)
Пример #30
0
    def start(self):
        self.startButton.setEnabled(False)

        QGuiApplication.setOverrideCursor(Qt.WaitCursor)

        self.bytesWritten = 0
        self.bytesReceived = 0

        while not self.tcpServer.isListening() and not self.tcpServer.listen():
            ret = QMessageBox.critical(
                self,
                self.tr("Loopback"),
                self.tr(
                    "Unable to start the test: %s" % (self.tcpServer.errorString())
                ),
                QMessageBox.Retry | QMessageBox.Cancel,
            )
            if ret == QMessageBox.Cancel:
                return

        self.serverStatusLabel.setText(self.tr("Listening"))
        self.clientStatusLabel.setText(self.tr("Connecting"))
        self.tcpClient.connectToHost(
            QHostAddress.LocalHost, self.tcpServer.serverPort()
        )
Пример #31
0
    def shortcuts_info(self):

        data = "Ctrl+Shift+N - togle node box\n"
        data += "Ctrl+N - new file\n"
        data += "Ctrl+S - save\n"
        data += "Ctrl+Shift+S - save as\n"
        data += "Ctrl+O - open file\n"
        data += "Ctrl+F - frame\n"
        data += "C - comment selected nodes\n"
        data += "Delete - kill selected nodes\n"
        data += "Ctrl+Shift+ArrowLeft - Align left\n"
        data += "Ctrl+Shift+ArrowUp - Align Up\n"
        data += "Ctrl+Shift+ArrowRight - Align right\n"
        data += "Ctrl+Shift+ArrowBottom - Align Bottom\n"

        QMessageBox.information(self, "Shortcuts", data)
Пример #32
0
    def doExport(pyFlowInstance):
        script = "// This file was auto-generated by PyFlow exporter '{0} v{1}'\n".format(
            CPPCompiler.displayName(), str(CPPCompiler.version()))
        script += "// Created: {0}\n\n".format(
            CPPCompiler.creationDateString())
        script += "#include <iostream>\n\n"
        script += "int main()\n"
        script += "{\n"

        rootGraph = pyFlowInstance.graphManager.get().findRootGraph()
        if len(rootGraph.getNodes()) == 0:
            QMessageBox.warning(pyFlowInstance, "Warning",
                                "Nothing to export!")
            return

        consoleOutNode = pyFlowInstance.graphManager.get().findNode(
            "consoleOutput")
        if consoleOutNode is None:
            QMessageBox.warning(pyFlowInstance, "Warning",
                                "Console out node not found")
            return

        consoleOutNode[DEFAULT_IN_EXEC_NAME].call()

        script += '\tstd::cout << "{}\\n";\n'.format(
            consoleOutNode["entity"].getData())

        script += "}\n"

        outFilePath, filterString = QFileDialog.getSaveFileName(
            filter="c++ source (*.cpp)")
        if outFilePath != "":
            with open(outFilePath, 'w') as f:
                f.write(script)
            cmd = [
                "g++.exe", outFilePath, "-std=c++11", "-o",
                outFilePath.replace(".cpp", ".exe")
            ]
            myEnv = os.environ.copy()
            proc = subprocess.Popen(cmd,
                                    shell=True,
                                    env=myEnv,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT)
            proc.communicate()
            print("EXE OUTPUT:",
                  subprocess.check_output(outFilePath.replace(".cpp", ".exe")))
Пример #33
0
    def closeEvent(self, event):
        """
        Called when the main window is closed
        """
        reply = QMessageBox.question(self, 'Message',
                                           "Are you sure to quit?", QMessageBox.Yes |
                                           QMessageBox.No, QMessageBox.Yes)

        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()