def findPath(self, index): path = self.sender().model().filePath(index) if os.path.isfile(path): global name FormWidget.filepath.append(path) name = os.path.basename(path) for i in range(self.tab.count()): if name == self.tab.tabText(i): self.tab.removeTab(i) break newEdit = QsciScintilla() self.checkExtensionToHighlight(path, newEdit) newEdit.setFont(QFont('Times', 10)) newEdit.setMarginType(0, QsciScintilla.NumberMargin) newEdit.setMarginWidth(0, '00000000') try: newEdit.setText(open(path).read()) newEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) newEdit.setAutoCompletionCaseSensitivity(False) newEdit.setAutoCompletionReplaceWord(False) newEdit.setAutoCompletionSource(QsciScintilla.AcsDocument) newEdit.setAutoCompletionThreshold(1) self.tab.insertTab(0, newEdit, QIcon('icon.png'), os.path.basename(path)) self.tab.setCurrentIndex(0) except: QMessageBox.warning(self, "Warning", "Unsupported file type", QMessageBox.Ok)
class TextEdit(BaseParamWidget): def __init__(self, layout_dir: str, title: str, initial_value: str = '', lexer=''): super().__init__(layout_dir) self.on_check_callback = None self.prefix = QLabel(text=title) entryLayout = QHBoxLayout() entryLayout.setContentsMargins(0, 0, 0, 0) self.ctrl = QsciScintilla() if lexer == 'python': self.ctrl.setLexer(QsciLexerPython()) self.ctrl.setText(initial_value) # self.ctrl.textChanged.connect(self.ontext) # self.postfix = lab_unit = QLabel(text=unit) self.central_layout.addWidget(self.prefix) self.central_layout.addLayout(entryLayout) entryLayout.addWidget(self.ctrl) self.set_value(initial_value) # entryLayout.addWidget(self.postfix) def get_value(self): return self.ctrl.text() def set_value(self, value: str): self.ctrl.setText(value)
def openFile(self): files = QFileDialog.getOpenFileNames(self, "Open", FormWidget.path) if files[0]: FormWidget.filepath = files[0] FormWidget.path = os.path.dirname(files[0][0]) self.form_widget.tree.setRootIndex( self.form_widget.model.index(FormWidget.path)) for i in files[0]: n = os.path.basename(i) for j in range(self.form_widget.tab.count()): if n == self.form_widget.tab.tabText(j): self.form_widget.tab.removeTab(j) break newEdit = QsciScintilla() newEdit.setFont(QFont('Times', 10)) newEdit.setMarginType(0, QsciScintilla.NumberMargin) newEdit.setMarginWidth(0, '00000000') self.form_widget.checkExtensionToHighlight(i, newEdit) try: newEdit.setText(open(i).read()) newEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) newEdit.setAutoCompletionCaseSensitivity(False) newEdit.setAutoCompletionReplaceWord(False) newEdit.setAutoCompletionSource(QsciScintilla.AcsDocument) newEdit.setAutoCompletionThreshold(1) self.form_widget.tab.insertTab(0, newEdit, QIcon('icon.png'), n) self.form_widget.tab.setCurrentIndex(0) except: QMessageBox.warning(self, 'Warning', 'Unsupported file type', QMessageBox.Ok)
def addEmptyTab(self): newTab = QtWidgets.QWidget() self.tabWidget.addTab(newTab, 'New Script') newTab.setToolTip('New Script') self.tabWidget.setCurrentWidget(newTab) tabGrid = QtWidgets.QGridLayout(newTab) tabGrid.setContentsMargins(2, 2, 2, 2) newSciInput = QsciScintilla(newTab) newSciInput.setFrameShape(QtWidgets.QFrame.Box) tabGrid.addWidget(newSciInput, 0, 0, 1, 1) self._setQSci(newSciInput) newSciInput.setText('') newSciInput.setFocus()
def create_qscintilla_code_view(): """ Create a QScintilla based view containing a copy of this source code. """ from PyQt5.Qsci import QsciLexerPython, QsciScintilla view = QsciScintilla() view.setReadOnly(True) view.setUtf8(True) view.setLexer(QsciLexerPython()) view.setFolding(QsciScintilla.PlainFoldStyle) view.setText(get_source_code()) return view
def addNewTab(self, scriptFile): print("Loading tab..." + scriptFile) fileName = os.path.basename(scriptFile) newTab = QtWidgets.QWidget() self.tabWidget.addTab(newTab, fileName) newTab.setToolTip(scriptFile) self.tabWidget.setCurrentWidget(newTab) tabGrid = QtWidgets.QGridLayout(newTab) tabGrid.setContentsMargins(2, 2, 2, 2) newSciInput = QsciScintilla(newTab) newSciInput.setFrameShape(QtWidgets.QFrame.Box) tabGrid.addWidget(newSciInput, 0, 0, 1, 1) self._setQSci(newSciInput) data = str(self.ttls.fileContent(scriptFile)) newSciInput.setText(data)
def createTabWidget(self, code, textLexer: QsciLexer): tabWidget = QWidget() # 垂直布局 layout = WidgetUtil.createVBoxLayout() # 设置布局方式 tabWidget.setLayout(layout) editor = QsciScintilla(tabWidget) editor.setLexer(textLexer) # 行号提示 editor.setMarginType(0, QsciScintilla.NumberMargin) # 设置编号为1的页边显示行号。 editor.setMarginLineNumbers(0, True) # 对该页边启用行号 editor.setMarginWidth(0, 30) # 设置页边宽度 editor.setText(code) editor.SendScintilla(QsciScintilla.SCI_SETCODEPAGE, QsciScintilla.SC_CP_UTF8) # 设置编码为UTF-8 editor.setReadOnly(True) # 添加控件到布局中 layout.addWidget(editor) return tabWidget
class CodeDialog(QDialog): codeChanged = pyqtSignal('QString') def __init__(self, code): super(QDialog, self).__init__() self.codeEdit = QsciScintilla() self.codeEdit.setText(code) fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.codeEdit.setFont(fixedWidthFont) fontmetrics = QFontMetrics(fixedWidthFont) self.codeEdit.setMarginWidth(0, fontmetrics.width("000")) self.codeEdit.setMarginLineNumbers(0, True) self.codeEdit.setMarginsBackgroundColor(QColor("#cccccc")) self.codeEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.codeEdit.setCaretLineVisible(True) self.codeEdit.setCaretLineBackgroundColor(QColor("#ffe4e4")) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.codeEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.codeEdit.setUtf8(True) self.codeEdit.setTabWidth(4) self.codeEdit.setIndentationsUseTabs(True) self.codeEdit.setIndentationGuides(True) self.codeEdit.setTabIndents(True) self.codeEdit.setAutoIndent(True) verticalLayout = QVBoxLayout() verticalLayout.addWidget(self.codeEdit) self.setLayout(verticalLayout) self.codeEdit.textChanged.connect(self.changeCode) def changeCode(self): self.codeChanged.emit(self.codeEdit.text())
def abrir_archivo(self): try: dialog = QtWidgets.QFileDialog().getOpenFileName( None, ' Open document', r"C:\Users\\", "All Files (*)") ruta = dialog[0] trozos = ruta.split("/") name = trozos[len(trozos) - 1] self.pestañas[name] = ruta file = open(ruta, 'r') codigo = file.read() tab = QtWidgets.QWidget() area = QsciScintilla(tab) area.setGeometry(QtCore.QRect(10, 10, 631, 371)) area.setObjectName("plainTextEdit") area.setFont(self.__myFont) area.setMarginType(0, QsciScintilla.NumberMargin) area.setMarginWidth(0, "00000") area.setMarginsForegroundColor(QtGui.QColor("#0C4B72")) area.markerDefine(QsciScintilla.RightArrow, 0) area.setMarginSensitivity(0, True) area.setWrapMode(QsciScintilla.WrapWord) area.setWrapVisualFlags(QsciScintilla.WrapFlagByText) area.setWrapIndentMode(QsciScintilla.WrapIndentIndented) area.setEolMode(QsciScintilla.EolWindows) area.setEolVisibility(False) area.setWrapVisualFlags(QsciScintilla.WrapFlagByText) area.marginClicked.connect(self.on_margin_clicked) __lexer = QsciLexerCPP(area) area.setLexer(__lexer) self.editor.addTab(tab, "") area.setText(codigo) area.setObjectName("area") self.editor.addTab(tab, name) file.close() except: em = QtWidgets.QErrorMessage(self.mw) em.showMessage("Error al abrir {0}".format(name))
class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("Proyecto") MainWindow.resize(1074, 588) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.btn_abrir = QtWidgets.QPushButton(self.centralwidget) self.btn_abrir.setGeometry(QtCore.QRect(970, 20, 61, 41)) self.btn_abrir.setObjectName("btn_abrir") self.btn_guardar = QtWidgets.QPushButton(self.centralwidget) self.btn_guardar.setGeometry(QtCore.QRect(970, 70, 61, 41)) self.btn_guardar.setObjectName("btn_guardar") self.btn_guardar_como = QtWidgets.QPushButton(self.centralwidget) self.btn_guardar_como.setGeometry(QtCore.QRect(970, 120, 61, 41)) self.btn_guardar_como.setObjectName("btn_guardar_como") self.btn_ejecutar = QtWidgets.QPushButton(self.centralwidget) self.btn_ejecutar.setGeometry(QtCore.QRect(960, 220, 81, 41)) self.btn_ejecutar.setObjectName("btn_ejecutar") self.btn_debug = QtWidgets.QPushButton(self.centralwidget) self.btn_debug.setGeometry(QtCore.QRect(970, 320, 61, 41)) self.btn_debug.setObjectName("btn_debug") self.btn_siguiente_paso = QtWidgets.QPushButton(self.centralwidget) self.btn_siguiente_paso.setGeometry(QtCore.QRect(970, 370, 61, 41)) self.btn_siguiente_paso.setObjectName("btn_siguiente_paso") self.tabWidget = QtWidgets.QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QtCore.QRect(0, 10, 941, 551)) self.tabWidget.setObjectName("tabWidget") self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.txt_consola = QtWidgets.QTextEdit(self.tab) self.txt_consola.setGeometry(QtCore.QRect(10, 410, 511, 101)) self.txt_consola.setObjectName("txt_consola") self.tabWidget_4 = QtWidgets.QTabWidget(self.tab) self.tabWidget_4.setGeometry(QtCore.QRect(0, 0, 531, 391)) self.tabWidget_4.setObjectName("tabWidget_4") self.tab_8 = QtWidgets.QWidget() self.tab_8.setObjectName("tab_8") self.tabWidget_3 = QtWidgets.QTabWidget(self.tab_8) self.tabWidget_3.setGeometry(QtCore.QRect(0, 0, 521, 361)) self.tabWidget_3.setObjectName("tabWidget_3") self.tab_10 = QtWidgets.QWidget() self.tab_10.setObjectName("tab_10") self.frame_txt_entrada = QtWidgets.QFrame(self.tab_10) self.frame_txt_entrada.setGeometry(QtCore.QRect(10, 10, 501, 321)) self.frame_txt_entrada.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_txt_entrada.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_txt_entrada.setObjectName("frame_txt_entrada") self.tabWidget_3.addTab(self.tab_10, "") self.tab_11 = QtWidgets.QWidget() self.tab_11.setObjectName("tab_11") self.frame_txt_entrada_sin_optimizar = QtWidgets.QFrame(self.tab_11) self.frame_txt_entrada_sin_optimizar.setGeometry( QtCore.QRect(10, 10, 501, 321)) self.frame_txt_entrada_sin_optimizar.setFrameShape( QtWidgets.QFrame.StyledPanel) self.frame_txt_entrada_sin_optimizar.setFrameShadow( QtWidgets.QFrame.Raised) self.frame_txt_entrada_sin_optimizar.setObjectName( "frame_txt_entrada_sin_optimizar") self.tabWidget_3.addTab(self.tab_11, "") self.tabWidget_4.addTab(self.tab_8, "") self.tabWidget_2 = QtWidgets.QTabWidget(self.tab) self.tabWidget_2.setGeometry(QtCore.QRect(540, 20, 391, 491)) self.tabWidget_2.setObjectName("tabWidget_2") self.tab_12 = QtWidgets.QWidget() self.tab_12.setObjectName("tab_12") self.frame_txt_minor_c = QtWidgets.QFrame(self.tab_12) self.frame_txt_minor_c.setGeometry(QtCore.QRect(10, 10, 361, 441)) self.frame_txt_minor_c.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_txt_minor_c.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_txt_minor_c.setObjectName("frame_txt_minor_c") self.tabWidget_2.addTab(self.tab_12, "") self.tab_5 = QtWidgets.QWidget() self.tab_5.setObjectName("tab_5") self.scrollArea_2 = QtWidgets.QScrollArea(self.tab_5) self.scrollArea_2.setGeometry(QtCore.QRect(10, 10, 361, 441)) self.scrollArea_2.setWidgetResizable(True) self.scrollArea_2.setObjectName("scrollArea_2") self.scrollAreaWidgetContents_2 = QtWidgets.QWidget() self.scrollAreaWidgetContents_2.setGeometry( QtCore.QRect(0, 0, 518, 422)) self.scrollAreaWidgetContents_2.setObjectName( "scrollAreaWidgetContents_2") self.horizontalLayout = QtWidgets.QHBoxLayout( self.scrollAreaWidgetContents_2) self.horizontalLayout.setObjectName("horizontalLayout") self.treeView = QtWidgets.QTreeView(self.scrollAreaWidgetContents_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.treeView.sizePolicy().hasHeightForWidth()) self.treeView.setSizePolicy(sizePolicy) self.treeView.setMinimumSize(QtCore.QSize(500, 0)) self.treeView.setLayoutDirection(QtCore.Qt.LeftToRight) self.treeView.setAnimated(True) self.treeView.setObjectName("treeView") self.horizontalLayout.addWidget(self.treeView) self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2) self.tabWidget_2.addTab(self.tab_5, "") self.tabWidget.addTab(self.tab, "") self.tab_2 = QtWidgets.QWidget() self.tab_2.setObjectName("tab_2") self.scrollArea_3 = QtWidgets.QScrollArea(self.tab_2) self.scrollArea_3.setGeometry(QtCore.QRect(10, 10, 681, 411)) self.scrollArea_3.setLayoutDirection(QtCore.Qt.LeftToRight) self.scrollArea_3.setWidgetResizable(True) self.scrollArea_3.setObjectName("scrollArea_3") self.scrollAreaWidgetContents_3 = QtWidgets.QWidget() self.scrollAreaWidgetContents_3.setGeometry( QtCore.QRect(0, 0, 679, 409)) self.scrollAreaWidgetContents_3.setObjectName( "scrollAreaWidgetContents_3") self.verticalLayout_2 = QtWidgets.QVBoxLayout( self.scrollAreaWidgetContents_3) self.verticalLayout_2.setObjectName("verticalLayout_2") self.lbl_graphviz = QtWidgets.QLabel(self.scrollAreaWidgetContents_3) self.lbl_graphviz.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.lbl_graphviz.setFrameShape(QtWidgets.QFrame.Panel) self.lbl_graphviz.setText("") self.lbl_graphviz.setScaledContents(False) self.lbl_graphviz.setObjectName("lbl_graphviz") self.verticalLayout_2.addWidget(self.lbl_graphviz) self.scrollArea_3.setWidget(self.scrollAreaWidgetContents_3) self.tabWidget.addTab(self.tab_2, "") self.tab_3 = QtWidgets.QWidget() self.tab_3.setObjectName("tab_3") self.scrollArea = QtWidgets.QScrollArea(self.tab_3) self.scrollArea.setGeometry(QtCore.QRect(10, 10, 681, 411)) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 679, 409)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.tab_reporte = QtWidgets.QTabWidget(self.scrollAreaWidgetContents) self.tab_reporte.setGeometry(QtCore.QRect(20, 10, 661, 381)) self.tab_reporte.setObjectName("tab_reporte") self.tab_4 = QtWidgets.QWidget() self.tab_4.setObjectName("tab_4") self.scrollArea_4 = QtWidgets.QScrollArea(self.tab_4) self.scrollArea_4.setGeometry(QtCore.QRect(0, 10, 641, 341)) self.scrollArea_4.setWidgetResizable(True) self.scrollArea_4.setObjectName("scrollArea_4") self.scrollAreaWidgetContents_4 = QtWidgets.QWidget() self.scrollAreaWidgetContents_4.setGeometry( QtCore.QRect(0, 0, 639, 339)) self.scrollAreaWidgetContents_4.setObjectName( "scrollAreaWidgetContents_4") self.verticalLayout = QtWidgets.QVBoxLayout( self.scrollAreaWidgetContents_4) self.verticalLayout.setObjectName("verticalLayout") self.tabla_etiqueta = QtWidgets.QTableWidget( self.scrollAreaWidgetContents_4) self.tabla_etiqueta.setObjectName("tabla_etiqueta") self.tabla_etiqueta.setColumnCount(0) self.tabla_etiqueta.setRowCount(0) self.verticalLayout.addWidget(self.tabla_etiqueta) self.scrollArea_4.setWidget(self.scrollAreaWidgetContents_4) self.tab_reporte.addTab(self.tab_4, "") self.tab_6 = QtWidgets.QWidget() self.tab_6.setObjectName("tab_6") self.scrollArea_5 = QtWidgets.QScrollArea(self.tab_6) self.scrollArea_5.setGeometry(QtCore.QRect(0, 10, 641, 341)) self.scrollArea_5.setWidgetResizable(True) self.scrollArea_5.setObjectName("scrollArea_5") self.scrollAreaWidgetContents_5 = QtWidgets.QWidget() self.scrollAreaWidgetContents_5.setGeometry( QtCore.QRect(0, 0, 639, 339)) self.scrollAreaWidgetContents_5.setObjectName( "scrollAreaWidgetContents_5") self.horizontalLayout_2 = QtWidgets.QHBoxLayout( self.scrollAreaWidgetContents_5) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.tabla_error = QtWidgets.QTableWidget( self.scrollAreaWidgetContents_5) self.tabla_error.setObjectName("tabla_error") self.tabla_error.setColumnCount(0) self.tabla_error.setRowCount(0) self.horizontalLayout_2.addWidget(self.tabla_error) self.scrollArea_5.setWidget(self.scrollAreaWidgetContents_5) self.tab_reporte.addTab(self.tab_6, "") self.tab_9 = QtWidgets.QWidget() self.tab_9.setObjectName("tab_9") self.textEdit = QtWidgets.QTextEdit(self.tab_9) self.textEdit.setGeometry(QtCore.QRect(10, 20, 631, 321)) self.textEdit.setObjectName("textEdit") self.tab_reporte.addTab(self.tab_9, "") self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.tabWidget.addTab(self.tab_3, "") self.tab_13 = QtWidgets.QWidget() self.tab_13.setObjectName("tab_13") self.tabWidget.addTab(self.tab_13, "") self.tab_7 = QtWidgets.QWidget() self.tab_7.setObjectName("tab_7") self.tabWidget.addTab(self.tab_7, "") self.btn_ejecutar_desc = QtWidgets.QPushButton(self.centralwidget) self.btn_ejecutar_desc.setGeometry(QtCore.QRect(960, 270, 81, 41)) self.btn_ejecutar_desc.setObjectName("btn_ejecutar_desc") self.btn_ejecutar_minor_c = QtWidgets.QPushButton(self.centralwidget) self.btn_ejecutar_minor_c.setGeometry(QtCore.QRect(950, 170, 101, 41)) self.btn_ejecutar_minor_c.setObjectName("btn_ejecutar_minor_c") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1074, 21)) self.menubar.setObjectName("menubar") self.menuArchivo = QtWidgets.QMenu(self.menubar) self.menuArchivo.setObjectName("menuArchivo") self.menuEditar = QtWidgets.QMenu(self.menubar) self.menuEditar.setObjectName("menuEditar") self.menuAnalisis = QtWidgets.QMenu(self.menubar) self.menuAnalisis.setObjectName("menuAnalisis") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionGuardar = QtWidgets.QAction(MainWindow) self.actionGuardar.setObjectName("actionGuardar") self.actionGuardar_Como = QtWidgets.QAction(MainWindow) self.actionGuardar_Como.setObjectName("actionGuardar_Como") self.actionGuardar_Como_2 = QtWidgets.QAction(MainWindow) self.actionGuardar_Como_2.setObjectName("actionGuardar_Como_2") self.actionAscendente = QtWidgets.QAction(MainWindow) self.actionAscendente.setObjectName("actionAscendente") self.actionDescendente = QtWidgets.QAction(MainWindow) self.actionDescendente.setObjectName("actionDescendente") self.actionReiniciar_Debug = QtWidgets.QAction(MainWindow) self.actionReiniciar_Debug.setObjectName("actionReiniciar_Debug") self.actionSiguiente_Paso_Debug = QtWidgets.QAction(MainWindow) self.actionSiguiente_Paso_Debug.setObjectName( "actionSiguiente_Paso_Debug") self.actionCopiar = QtWidgets.QAction(MainWindow) self.actionCopiar.setObjectName("actionCopiar") self.actionPegar = QtWidgets.QAction(MainWindow) self.actionPegar.setObjectName("actionPegar") self.actionBuscar = QtWidgets.QAction(MainWindow) self.actionBuscar.setObjectName("actionBuscar") self.actionReemplazar = QtWidgets.QAction(MainWindow) self.actionReemplazar.setObjectName("actionReemplazar") self.menuArchivo.addAction(self.actionGuardar) self.menuArchivo.addAction(self.actionGuardar_Como) self.menuArchivo.addAction(self.actionGuardar_Como_2) self.menuEditar.addAction(self.actionCopiar) self.menuEditar.addAction(self.actionPegar) self.menuEditar.addAction(self.actionBuscar) self.menuEditar.addAction(self.actionReemplazar) self.menuAnalisis.addAction(self.actionAscendente) self.menuAnalisis.addAction(self.actionDescendente) self.menuAnalisis.addAction(self.actionReiniciar_Debug) self.menuAnalisis.addAction(self.actionSiguiente_Paso_Debug) self.menubar.addAction(self.menuArchivo.menuAction()) self.menubar.addAction(self.menuEditar.menuAction()) self.menubar.addAction(self.menuAnalisis.menuAction()) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) self.tabWidget_4.setCurrentIndex(0) self.tabWidget_3.setCurrentIndex(0) self.tabWidget_2.setCurrentIndex(0) self.tab_reporte.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) self.__myFont = QFont() self.__myFont.setPointSize(12) #=========================================================EDITORES=================================== self.txt_minor_c = QsciScintilla() self.txt_minor_c.setText("") self.txt_minor_c.setUtf8(True) self.txt_minor_c.setFont(self.__myFont) # AJUSTES DE TEXTO self.txt_minor_c.setWrapMode(QsciScintilla.WrapWord) self.txt_minor_c.setWrapVisualFlags(QsciScintilla.WrapFlagByText) self.txt_minor_c.setWrapIndentMode(QsciScintilla.WrapIndentIndented) # FIN DE LINEA self.txt_minor_c.setEolMode(QsciScintilla.EolWindows) self.txt_minor_c.setEolVisibility(False) # SANGRIA self.txt_minor_c.setIndentationsUseTabs(False) self.txt_minor_c.setTabWidth(4) self.txt_minor_c.setIndentationGuides(True) self.txt_minor_c.setTabIndents(True) self.txt_minor_c.setAutoIndent(True) self.txt_minor_c.setCaretForegroundColor(QColor("#ff0000ff")) self.txt_minor_c.setCaretLineVisible(True) self.txt_minor_c.setCaretLineBackgroundColor(QColor("#1f0000ff")) self.txt_minor_c.setCaretWidth(2) # MARGENES self.txt_minor_c.setMarginType(0, QsciScintilla.NumberMargin) self.txt_minor_c.setMarginWidth( 0, "0000") # con este se puede quitar la linea self.txt_minor_c.setMarginsForegroundColor(QColor("#ff888888")) # SE COLOCAN LAS REGLAS DEL EDITOR self.__lexer = QsciLexerCPP(self.txt_minor_c) self.txt_minor_c.setLexer(self.__lexer) self.__lyt = QVBoxLayout() self.frame_txt_minor_c.setLayout(self.__lyt) self.__lyt.addWidget(self.txt_minor_c) #====================================ENTRADA=========================== self.txt_entrada = QsciScintilla() self.txt_entrada.setText("") self.txt_entrada.setUtf8(True) self.txt_entrada.setFont(self.__myFont) # AJUSTES DE TEXTO self.txt_entrada.setWrapMode(QsciScintilla.WrapWord) self.txt_entrada.setWrapVisualFlags(QsciScintilla.WrapFlagByText) self.txt_entrada.setWrapIndentMode(QsciScintilla.WrapIndentIndented) # FIN DE LINEA self.txt_entrada.setEolMode(QsciScintilla.EolWindows) self.txt_entrada.setEolVisibility(False) # SANGRIA self.txt_entrada.setIndentationsUseTabs(False) self.txt_entrada.setTabWidth(4) self.txt_entrada.setIndentationGuides(True) self.txt_entrada.setTabIndents(True) self.txt_entrada.setAutoIndent(True) self.txt_entrada.setCaretForegroundColor(QColor("#ff0000ff")) self.txt_entrada.setCaretLineVisible(True) self.txt_entrada.setCaretLineBackgroundColor(QColor("#1f0000ff")) self.txt_entrada.setCaretWidth(2) # MARGENES self.txt_entrada.setMarginType(0, QsciScintilla.NumberMargin) self.txt_entrada.setMarginWidth( 0, "0000") # con este se puede quitar la linea self.txt_entrada.setMarginsForegroundColor(QColor("#ff888888")) # SE COLOCAN LAS REGLAS DEL EDITOR self.__lexer = QsciLexerRuby(self.txt_entrada) self.txt_entrada.setLexer(self.__lexer) self.__lyt = QVBoxLayout() self.frame_txt_entrada.setLayout(self.__lyt) self.__lyt.addWidget(self.txt_entrada) #========================Entrada Sin Optimizar====================== self.txt_entrada_sin_optimizar = QsciScintilla() self.txt_entrada_sin_optimizar.setText("") self.txt_entrada_sin_optimizar.setUtf8(True) self.txt_entrada_sin_optimizar.setFont(self.__myFont) # AJUSTES DE TEXTO self.txt_entrada_sin_optimizar.setWrapMode(QsciScintilla.WrapWord) self.txt_entrada_sin_optimizar.setWrapVisualFlags( QsciScintilla.WrapFlagByText) self.txt_entrada_sin_optimizar.setWrapIndentMode( QsciScintilla.WrapIndentIndented) # FIN DE LINEA self.txt_entrada_sin_optimizar.setEolMode(QsciScintilla.EolWindows) self.txt_entrada_sin_optimizar.setEolVisibility(False) # SANGRIA self.txt_entrada_sin_optimizar.setIndentationsUseTabs(False) self.txt_entrada_sin_optimizar.setTabWidth(4) self.txt_entrada_sin_optimizar.setIndentationGuides(True) self.txt_entrada_sin_optimizar.setTabIndents(True) self.txt_entrada_sin_optimizar.setAutoIndent(True) self.txt_entrada_sin_optimizar.setCaretForegroundColor( QColor("#ff0000ff")) self.txt_entrada_sin_optimizar.setCaretLineVisible(True) self.txt_entrada_sin_optimizar.setCaretLineBackgroundColor( QColor("#1f0000ff")) self.txt_entrada_sin_optimizar.setCaretWidth(2) # MARGENES self.txt_entrada_sin_optimizar.setMarginType( 0, QsciScintilla.NumberMargin) self.txt_entrada_sin_optimizar.setMarginWidth( 0, "0000") # con este se puede quitar la linea self.txt_entrada_sin_optimizar.setMarginsForegroundColor( QColor("#ff888888")) # SE COLOCAN LAS REGLAS DEL EDITOR self.__lexer = QsciLexerRuby(self.txt_entrada_sin_optimizar) self.txt_entrada_sin_optimizar.setLexer(self.__lexer) self.__lyt = QVBoxLayout() self.frame_txt_entrada_sin_optimizar.setLayout(self.__lyt) self.__lyt.addWidget(self.txt_entrada_sin_optimizar) #====================================================================== #Para Abrir,Guardar,Como self.btn_abrir.clicked.connect(self.abrir_archivo) self.actionGuardar.triggered.connect(self.abrir_archivo) self.btn_guardar_como.clicked.connect(self.guardar_archivo_como) self.actionGuardar_Como_2.triggered.connect(self.guardar_archivo_como) self.actionGuardar_Como.triggered.connect(self.guardar_archivo) self.btn_guardar.clicked.connect(self.guardar_archivo) #Ejecucion self.btn_ejecutar.clicked.connect(self.parser) self.actionAscendente.triggered.connect(self.parser) self.btn_ejecutar_desc.clicked.connect(self.parser_descendente) self.actionDescendente.triggered.connect(self.parser_descendente) self.btn_debug.clicked.connect(self.parser_paso_iniciar) self.actionReiniciar_Debug.triggered.connect(self.parser_paso_iniciar) self.btn_siguiente_paso.clicked.connect(self.parser_paso_ejecutar) self.actionSiguiente_Paso_Debug.triggered.connect( self.parser_paso_ejecutar) self.btn_ejecutar_minor_c.clicked.connect(self.ejecutar_main_c) def ejecutar_main_c(self): from AProyecto2.Main import analizar_minor_c, analizar_minor_c_optimizar_3D rst = analizar_minor_c_optimizar_3D(self.txt_minor_c.text()) self.txt_entrada.setText(rst) def graficar_arbol(self): import pydot global Ts dot_string = Ts.generar_dot() graphs = pydot.graph_from_dot_data(dot_string) from PyQt5.QtWidgets import QApplication # app = QApplication(sys.argv) # win = QWidget() # l1 = QLabel() from PyQt5.QtGui import QPixmap qp = QPixmap() qp.loadFromData(graphs[0].create_png()) self.lbl_graphviz.resize(qp.size()) # m_imageLabel->resize(m_scaleFactor * m_imageLabel->size()); self.lbl_graphviz.setPixmap(qp) # vbox = QVBoxLayout() # vbox.addWidget(l1) # win.setLayout(vbox) # win.setWindowTitle("QPixmap Demo") # win.show() # sys.exit(app.exec_()) archivo_actual = None def guardar_archivo(self): if self.archivo_actual is None: self.guardar_archivo_como() else: file = open(self.archivo_actual, 'w') text = self.txt_entrada.text() file.write(text) self.color(text) def guardar_archivo_como(self): try: fname = QFileDialog.getSaveFileName() file = open(fname[0], 'w') text = self.txt_entrada.text() file.write(text) self.color(text) except: pass def abrir_archivo(self): try: fname = QFileDialog.getOpenFileName() f = open(fname[0], "r") input: str = f.read() self.color(input) self.archivo_actual = fname[0] self.txt_minor_c.setText(input) except: pass def color(self, input): return def parser_paso_iniciar(self): self.pasex = 1 self.ejecutar_main_c() try: self.txt_consola.clear() dim = self.txt_entrada.text() input = dim global Ts Ts.guardar_consola(self.txt_consola) Ts.nueva_ejecucion(input) raiz_produccion: ListaInstruccion = analizar_ascendente(input) self.raiz_global = raiz_produccion Ts.guardar_tabla_etiqueta(self.tabla_etiqueta) Ts.guardar_tabla_error(self.tabla_error) if raiz_produccion is not None: Ts.cargar_etiquetas(raiz_produccion) else: Ts.mensaje_info("Error", "Error En El Codigo") #self.color() self.graficar_arbol() treeView = self.treeView treeView.setHeaderHidden(True) Ts.guardar_arbol(treeView) Ts.actualizar_arbol() self.textEdit.clear() self.textEdit.append("<div contenteditable>" + Ts.rp_cabecera() + "</div>") except: import sys Ts.mensaje_info("Error", "Error Durante El Analisis") print("Oops!", sys.exc_info()[0], "occurred.") raiz_global = None pasex = 1 def parser_paso_ejecutar(self): try: if self.raiz_global is not None: #DEFAULT_INDICATOR_ID = 1 #self.txt_entrada.indicatorDefine(QsciScintilla.FullBoxIndicator, self.pasex) #self.txt_entrada.fillIndicatorRange(self.pasex, 0, self.pasex + 1, 0, self.pasex) #self.pasex+=1 #print(self.pasex) ex = Ts.paso_a_paso_ejecutar() if ex == "exit": Ts.mensaje_info("Informacion", "Ejecucion Paso A Paso Completo") self.raiz_global = None treeView = self.treeView treeView.setHeaderHidden(True) Ts.guardar_arbol(treeView) Ts.actualizar_arbol() else: Ts.mensaje_info("Ejecucion", "No hay nada que ejecutar") except: import sys Ts.mensaje_info("Error", "Error Durante El Analisis") print("Oops!", sys.exc_info()[0], "occurred.") def parser(self): try: self.txt_consola.clear() global Ts Ts.guardar_consola(self.txt_consola) dim = self.txt_entrada.text() input = dim Ts.nueva_ejecucion(input) raiz_produccion: ListaInstruccion = analizar_ascendente(input) Ts.guardar_tabla_etiqueta(self.tabla_etiqueta) Ts.guardar_tabla_error(self.tabla_error) if raiz_produccion is not None: Ts.cargar_etiquetas(raiz_produccion) Ts.ejecutar_main() else: Ts.mensaje_info("Error", "Error En El Codigo ") #self.color() self.graficar_arbol() treeView = self.treeView treeView.setHeaderHidden(True) Ts.guardar_arbol(treeView) Ts.actualizar_arbol() self.textEdit.clear() self.textEdit.append("<div contenteditable>" + Ts.rp_cabecera() + "</div>") except: import sys Ts.mensaje_info("Error", "Error Durante El Analisis") print("Oops!", sys.exc_info()[0], "occurred.") def parser_descendente(self): try: self.txt_consola.clear() global Ts Ts.guardar_consola(self.txt_consola) dim = self.txt_entrada.text() input = dim Ts.nueva_ejecucion(input) from Contenido.Analizadores.SintacticoDescendente import analizar_descendente raiz_produccion: ListaInstruccion = analizar_descendente(input) Ts.guardar_tabla_etiqueta(self.tabla_etiqueta) Ts.guardar_tabla_error(self.tabla_error) if raiz_produccion is not None: Ts.cargar_etiquetas(raiz_produccion) Ts.ejecutar_main() else: Ts.mensaje_info("Error", "Error En El Codigo") #self.color() self.graficar_arbol() treeView = self.treeView treeView.setHeaderHidden(True) Ts.guardar_arbol(treeView) Ts.actualizar_arbol() self.textEdit.clear() self.textEdit.append("<div contenteditable>" + Ts.rp_cabecera() + "</div>") except: import sys Ts.mensaje_info("Error", "Error Durante El Analisis") print("Oops!", sys.exc_info()[0], "occurred.") def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.btn_abrir.setText(_translate("MainWindow", "Abrir")) self.btn_guardar.setText(_translate("MainWindow", "Guardar")) self.btn_guardar_como.setText( _translate("MainWindow", "Guardar\n" "Como")) self.btn_ejecutar.setText( _translate("MainWindow", "Ejecutar\n" "Ascendente")) self.btn_debug.setText(_translate("MainWindow", "Debug")) self.btn_siguiente_paso.setText( _translate("MainWindow", "Siguiente\n" "Paso")) self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_10), _translate("MainWindow", "Optimizada")) self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_11), _translate("MainWindow", "Sin Optimizar")) self.tabWidget_4.setTabText( self.tabWidget_4.indexOf(self.tab_8), _translate("MainWindow", "Salida De MinorC")) self.tabWidget_2.setTabText( self.tabWidget_2.indexOf(self.tab_12), _translate("MainWindow", "Entrada Minor C")) self.tabWidget_2.setTabText( self.tabWidget_2.indexOf(self.tab_5), _translate("MainWindow", "Tabla De Simbolos")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Archivo Entrada")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Visualizar")) self.tab_reporte.setTabText(self.tab_reporte.indexOf(self.tab_4), _translate("MainWindow", "Etiquetas")) self.tab_reporte.setTabText(self.tab_reporte.indexOf(self.tab_6), _translate("MainWindow", "Errores")) self.tab_reporte.setTabText(self.tab_reporte.indexOf(self.tab_9), _translate("MainWindow", "Gramatical")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Reporte")) self.tabWidget.setTabText( self.tabWidget.indexOf(self.tab_13), _translate("MainWindow", "Visualizar Minor C")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_7), _translate("MainWindow", "Reporte Minor C")) self.btn_ejecutar_desc.setText( _translate("MainWindow", "Ejecutar\n" "Descendente")) self.btn_ejecutar_minor_c.setText( _translate("MainWindow", "Ejecutar Minor C")) self.menuArchivo.setTitle(_translate("MainWindow", "Archivo")) self.menuEditar.setTitle(_translate("MainWindow", "Editar")) self.menuAnalisis.setTitle(_translate("MainWindow", "Analisis")) self.actionGuardar.setText(_translate("MainWindow", "Abrir")) self.actionGuardar_Como.setText(_translate("MainWindow", "Guardar")) self.actionGuardar_Como_2.setText( _translate("MainWindow", "Guardar Como")) self.actionAscendente.setText(_translate("MainWindow", "Ascendente")) self.actionDescendente.setText(_translate("MainWindow", "Descendente")) self.actionReiniciar_Debug.setText( _translate("MainWindow", "Reiniciar Debug")) self.actionSiguiente_Paso_Debug.setText( _translate("MainWindow", "Siguiente Paso Debug")) self.actionCopiar.setText(_translate("MainWindow", "Copiar")) self.actionPegar.setText(_translate("MainWindow", "Pegar")) self.actionBuscar.setText(_translate("MainWindow", "Buscar")) self.actionReemplazar.setText(_translate("MainWindow", "Reemplazar"))
class CodeDialog(QDialog): codeChanged = pyqtSignal('QString') def __init__(self, name, currentValue): super(QDialog, self).__init__() self.setWindowTitle(name) self.resize(800, 600) self.codeEdit = QsciScintilla() self.codeEdit.setText(currentValue) fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.codeEdit.setFont(fixedWidthFont) fontmetrics = QFontMetrics(fixedWidthFont) self.codeEdit.setMarginWidth(0, fontmetrics.width("000")) self.codeEdit.setMarginLineNumbers(0, True) self.codeEdit.setMarginsBackgroundColor(QColor("#cccccc")) self.codeEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.codeEdit.setCaretLineVisible(True) self.codeEdit.setCaretLineBackgroundColor(QColor("#ffe4e4")) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.codeEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.codeEdit.setUtf8(True) self.codeEdit.setTabWidth(4) self.codeEdit.setIndentationsUseTabs(True) self.codeEdit.setIndentationGuides(True) self.codeEdit.setTabIndents(True) self.codeEdit.setAutoIndent(True) self.cancelButton = QPushButton('Cancel') self.cancelButton.clicked.connect(self.cancel) self.acceptButton = QPushButton('Accept') self.acceptButton.clicked.connect(self.accept) self.pythonButton = QRadioButton('Python') self.pythonButton.setChecked(True) self.pythonButton.clicked.connect(self.pythonClicked) self.cppButton = QRadioButton('C++') self.cppButton.clicked.connect(self.cppClicked) hLayout0 = QHBoxLayout() hLayout0.addWidget(self.pythonButton) hLayout0.addWidget(self.cppButton) container0 = QWidget() container0.setLayout(hLayout0) verticalLayout = QVBoxLayout() verticalLayout.addWidget(container0) verticalLayout.addWidget(self.codeEdit) container = QWidget() hLayout = QHBoxLayout() hLayout.addWidget(self.cancelButton) hLayout.addWidget(self.acceptButton) container.setLayout(hLayout) verticalLayout.addWidget(container) self.setLayout(verticalLayout) self.language = 'python' def cancel(self): self.close() def accept(self): self.codeChanged.emit(self.codeEdit.text()) self.close() def pythonClicked(self): fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.language = 'python' def cppClicked(self): fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) lexer = QsciLexerCPP() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.language = 'cpp'
class CustomMainWindow(QMainWindow): def __init__(self): super(CustomMainWindow, self).__init__() # -------------------------------- # # Window setup # # -------------------------------- # # 1. Define the geometry of the main window # ------------------------------------------ self.setGeometry(300, 300, 800, 400) self.setWindowTitle("QScintilla Test") # 2. Create frame and layout # --------------------------- self.__frm = QFrame(self) self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }") self.__lyt = QVBoxLayout() self.__frm.setLayout(self.__lyt) self.setCentralWidget(self.__frm) self.__myFont = QFont() self.__myFont.setPointSize(14) # 3. Place a button # ------------------ self.__btn = QPushButton("Qsci") self.__btn.setFixedWidth(50) self.__btn.setFixedHeight(50) self.__btn.clicked.connect(self.__btn_action) self.__btn.setFont(self.__myFont) self.__lyt.addWidget(self.__btn) # -------------------------------- # # QScintilla editor setup # # -------------------------------- # # ! Make instance of QSciScintilla class! # ---------------------------------------- self.__editor = QsciScintilla() self.__editor.setText("This\n") # Line 1 self.__editor.append("is\n") # Line 2 self.__editor.append("a\n") # Line 3 self.__editor.append("QScintilla\n") # Line 4 self.__editor.append("test\n") # Line 5 self.__editor.append("program\n") # Line 6 self.__editor.append("to\n") # Line 7 self.__editor.append("illustrate\n") # Line 8 self.__editor.append("some\n") # Line 9 self.__editor.append("basic\n") # Line 10 self.__editor.append("functions.") # Line 11 self.__editor.setLexer(None) self.__editor.setUtf8(True) # Set encoding to UTF-8 self.__editor.setFont(self.__myFont) # 1. Text wrapping # ----------------- self.__editor.setWrapMode(QsciScintilla.WrapWord) self.__editor.setWrapVisualFlags(QsciScintilla.WrapFlagByText) self.__editor.setWrapIndentMode(QsciScintilla.WrapIndentIndented) # 2. End-of-line mode # -------------------- self.__editor.setEolMode(QsciScintilla.EolWindows) self.__editor.setEolVisibility(False) # 3. Indentation # --------------- self.__editor.setIndentationsUseTabs(False) self.__editor.setTabWidth(4) self.__editor.setIndentationGuides(True) self.__editor.setTabIndents(True) self.__editor.setAutoIndent(True) # 4. Caret # --------- self.__editor.setCaretForegroundColor(QColor("#ff0000ff")) self.__editor.setCaretLineVisible(True) self.__editor.setCaretLineBackgroundColor(QColor("#1f0000ff")) self.__editor.setCaretWidth(2) # 5. Margins # ----------- # Margin 0 = Line nr margin self.__editor.setMarginType(0, QsciScintilla.NumberMargin) self.__editor.setMarginWidth(0, "0000") self.__editor.setMarginsForegroundColor(QColor("#ff888888")) # Margin 1 = Symbol margin self.__editor.setMarginType(1, QsciScintilla.SymbolMargin) self.__editor.setMarginWidth(1, "00000") sym_0 = QImage("icons/sym_0.png").scaled(QSize(16, 16)) sym_1 = QImage("icons/sym_1.png").scaled(QSize(16, 16)) sym_2 = QImage("icons/sym_2.png").scaled(QSize(16, 16)) sym_3 = QImage("icons/sym_3.png").scaled(QSize(16, 16)) self.__editor.markerDefine(sym_0, 0) self.__editor.markerDefine(sym_1, 1) self.__editor.markerDefine(sym_2, 2) self.__editor.markerDefine(sym_3, 3) self.__editor.setMarginMarkerMask(1, 0b1111) # 6. Margin mouse clicks # ----------------------- self.__editor.setMarginSensitivity(1, True) self.__editor.marginClicked.connect(self.__margin_left_clicked) self.__editor.marginRightClicked.connect(self.__margin_right_clicked) # ! Add editor to layout ! # ------------------------- self.__lyt.addWidget(self.__editor) self.show() '''''' def __margin_left_clicked(self, margin_nr, line_nr, state): print("Margin clicked (left mouse btn)!") print(" -> margin_nr: " + str(margin_nr)) print(" -> line_nr: " + str(line_nr)) print("") if state == Qt.ControlModifier: # Show green dot. self.__editor.markerAdd(line_nr, 0) elif state == Qt.ShiftModifier: # Show green arrow. self.__editor.markerAdd(line_nr, 1) elif state == Qt.AltModifier: # Show red dot. self.__editor.markerAdd(line_nr, 2) else: # Show red arrow. self.__editor.markerAdd(line_nr, 3) '''''' def __margin_right_clicked(self, margin_nr, line_nr, state): print("Margin clicked (right mouse btn)!") print(" -> margin_nr: " + str(margin_nr)) print(" -> line_nr: " + str(line_nr)) print("") '''''' def __btn_action(self): print("Hello World!") ''''''
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.qfont = QFont() self.qfont.setPointSize(11) self.qscintilla = QsciScintilla() self.qscintilla.setWrapMode (QsciScintilla.SC_WRAP_NONE) self.ui.verticalLayout.addWidget(self.qscintilla) self.qscintilla.textChanged.connect(self.acpiTblCntChanged) self.qscintilla.setFont(self.qfont) self.ui.pushButton.clicked.connect(self.compilePushButton) self.ui.pushButton.setEnabled(False) self.ui.pushButton_2.clicked.connect(self.loadPushButton) self.ui.pushButton_2.setEnabled(False) self.ui.pushButton_3.clicked.connect(self.debugOnPushButton) self.ui.pushButton_4.clicked.connect(self.debugOffPushButton) self.ui.pushButton_5.clicked.connect(self.searchPushButton) self.ui.checkBox.stateChanged.connect(self.woCheckBox) self.ui.checkBox_2.stateChanged.connect(self.csCheckBox) self.wo, self.cs = False, False self.msgBox = QMessageBox() # Show ACPI tbl in QListView self.acpiRegTblList = GetEnumKeyList (winreg.HKEY_LOCAL_MACHINE, ACPI_REG_KEY_PATH) self.ctnRegTblList = list() # Collect needed external control method AML for regTbl in self.acpiRegTblList: if re.match(r'SSD.|DSDT', regTbl): self.ctnRegTblList.append (regTbl) # Extract AMLs for regTbl in self.ctnRegTblList: subprocess.run ([aslExePath, '/nologo', '/tab=' + regTbl, '/c'], encoding='utf-8', capture_output=False) self.extCtnAmlList = [f for f in cfg['EXT_CTN_AML_DIR'] if os.path.exists(f)] acpiSlm = QStringListModel() acpiSlm.setStringList(self.ctnRegTblList) self.ui.listView.setModel(acpiSlm) self.ui.listView.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) self.tblName = str() self.acpiModelIndex = QModelIndex() self.ui.listView.clicked.connect(self.clickedListView) def clickedListView(self, qModelIndex): if self.acpiModelIndex == qModelIndex: return # Disable Compile pushButton self.ui.pushButton.setEnabled(False) # Disable Load pushButton self.ui.pushButton_2.setEnabled(False) self.acpiModelIndex = qModelIndex # Run asl.exe to get AML self.tblName = self.ctnRegTblList[qModelIndex.row()] # Extract needed external control method AML subProcArgs = [iAslExePath, '-vs', '-p' + self.tblName, '-e'] for regTbl in self.ctnRegTblList: if regTbl != self.tblName: subProcArgs.append(regTbl + REGEDIT_AML_POSTFIX) for extTbl in self.extCtnAmlList: subProcArgs.append(extTbl) subProcArgs.extend (['-d', self.tblName + REGEDIT_AML_POSTFIX]) tblCnt = str() # Use iasl.exe to disassemble AML self.ui.statusbar.showMessage('Disassembling ' + self.tblName) status = subprocess.run (subProcArgs, encoding='utf-8', capture_output=True) if status.returncode: self.ui.statusbar.showMessage(self.tblName + ' disassembled failed') self.msgBox.setText(self.tblName + ' disassembled failed!') self.popErrMsgBox(status.stderr) else: self.ui.statusbar.clearMessage() print(status.stderr) with open (self.tblName + OUTPUT_ASL_POSTFIX, 'r') as tbl: tblCnt = tbl.read() self.qscintilla.setText(tblCnt) def acpiTblCntChanged(self): self.ui.pushButton.setEnabled(True) def woCheckBox (self): if self.ui.checkBox.isChecked(): self.wo = True else: self.wo = False def csCheckBox (self): if self.ui.checkBox_2.isChecked(): self.cs = True else: self.cs = False def compilePushButton(self): with open (self.tblName + OUTPUT_ASL_POSTFIX, 'w') as tbl: tbl.write(self.qscintilla.text()) status = subprocess.run ([iAslExePath, '-ve', self.tblName + OUTPUT_ASL_POSTFIX], encoding='utf-8', capture_output=True) if not status.returncode: self.ui.pushButton.setEnabled(False) self.ui.pushButton_2.setEnabled(True) print(status.stdout) else: self.msgBox.setText(self.tblName + ' compiled error!') self.popErrMsgBox(status.stderr) def popErrMsgBox(self, errStr): self.msgBox.setWindowTitle('ERROR') self.msgBox.setInformativeText(errStr) self.msgBox.setStandardButtons(QMessageBox.StandardButton.Ok) self.msgBox.setDefaultButton(QMessageBox.StandardButton.Ok) return self.msgBox.exec() def popMsgBox(self): self.msgBox.setWindowTitle('LOAD') self.msgBox.setText(self.tblName + ' is going load into registry !') self.msgBox.setInformativeText('Do you want to apply it ?') self.msgBox.setStandardButtons(QMessageBox.StandardButton.Apply | QMessageBox.StandardButton.Cancel) self.msgBox.setDefaultButton(QMessageBox.StandardButton.Apply) return self.msgBox.exec() def loadPushButton(self): rtn = self.popMsgBox() if rtn == QMessageBox.StandardButton.Apply: status = subprocess.run ([aslExePath, '/loadtable', self.tblName + AML_POSTFIX], encoding='utf-8', shell=True) if status.returncode: self.ui.pushButton_2.setEnabled(False) else: self.popErrMsgBox(status.stderr) else: pass def searchPushButton(self): s = self.ui.lineEdit.text() self.qscintilla.findFirst(s, False, self.cs, self.wo, True, True) def debugOnPushButton(self): status = subprocess.run(['bcdedit', '/set', 'testsigning', 'on'], encoding='utf-8', shell=True) print ('Return Code:', status.returncode) def debugOffPushButton(self): status = subprocess.run(['bcdedit', '/set', 'testsigning', 'off'], encoding='utf-8', shell=True) print ('Return Code:', status.returncode)
class JsonEditorDlg(QtWidgets.QDialog): """Dialog widget for JsonEditor.""" def __init__(self, path, name, label_name, json, parent=None): super(JsonEditorDlg, self).__init__(parent) self.setWindowTitle("Json Editor") self._path = path self._name = name self._label_name = label_name self.orig_text = json self._label_file = QtWidgets.QLabel(label_name + ": " + name, self) self._save_button = QtWidgets.QPushButton("Save ...", self) self._save_button.clicked.connect(self._save_file) self._save_as_button = QtWidgets.QPushButton("Save as...", self) self._save_as_button.clicked.connect(self._save_as_file) self._cancel_button = QtWidgets.QPushButton("Cancel", self) self._cancel_button.clicked.connect(self._cancel) self._editor = QsciScintilla(self) # Set Yaml lexer self._editor.lexer = QsciLexerJavaScript() self._editor.setLexer(self._editor.lexer) self._editor.setMinimumSize(600, 450) self._editor.setText(json) appearance.set_default_appearence(self._editor) button_layout = QtWidgets.QHBoxLayout() button_layout.addWidget(self._label_file) button_layout.addWidget(self._save_button) button_layout.addWidget(self._save_as_button) button_layout.addWidget(self._cancel_button) layout = QtWidgets.QVBoxLayout(self) layout.addLayout(button_layout) layout.addWidget(self._editor) self.setLayout(layout) def _save_file(self): """Save json file""" try: file_name = os.path.join(self._path, self._name + ".json") file_d = open(file_name, 'w') file_d.write(self._editor.text()) file_d.close() except (RuntimeError, IOError) as err: err_dialog = gm_base.geomop_dialogs.GMErrorDialog(self) err_dialog.open_error_dialog("Can't save file", err) def _save_as_file(self): """Save json file as""" file_name = os.path.join(self._path, self._name + ".json") json_file = QtWidgets.QFileDialog.getSaveFileName( self, "Set Json File", file_name, "Json Files (*.json)") if json_file[0]: new_name = os.path.split(json_file[0])[1][:-5] new_path = os.path.split(json_file[0])[0] self._name = new_name self._path = new_path self._label_file.setText(self._label_name + ": " + new_name) self._save_file() def _cancel(self): """Cancel dialog""" # ToDo:if is there chnges, ask for save self.done(0)
class TransitionCodeDialog(QDialog): codeChanged = pyqtSignal('int', 'QString', 'QString') def __init__(self, name, transition): super(QDialog, self).__init__() self.transition = transition self.setWindowTitle(name) self.resize(800, 600) self.codeEdit = QsciScintilla() self.codeEdit.setText(self.transition.getCode()) fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.codeEdit.setFont(fixedWidthFont) fontmetrics = QFontMetrics(fixedWidthFont) self.codeEdit.setMarginWidth(0, fontmetrics.width("000")) self.codeEdit.setMarginLineNumbers(0, True) self.codeEdit.setMarginsBackgroundColor(QColor("#cccccc")) self.codeEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.codeEdit.setCaretLineVisible(True) self.codeEdit.setCaretLineBackgroundColor(QColor("#ffe4e4")) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.codeEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.codeEdit.setUtf8(True) self.codeEdit.setTabWidth(4) self.codeEdit.setIndentationsUseTabs(True) self.codeEdit.setIndentationGuides(True) self.codeEdit.setTabIndents(True) self.codeEdit.setAutoIndent(True) self.cancelButton = QPushButton('Cancel') self.cancelButton.clicked.connect(self.cancel) self.acceptButton = QPushButton('Accept') self.acceptButton.clicked.connect(self.accept) self.language = 'python' self.pythonButton = QRadioButton('Python') self.pythonButton.setChecked(True) self.pythonButton.clicked.connect(self.pythonClicked) self.cppButton = QRadioButton('C++') self.cppButton.clicked.connect(self.cppClicked) codeLanguageContainer = QWidget() hLayout0 = QHBoxLayout() hLayout0.addWidget(self.pythonButton) hLayout0.addWidget(self.cppButton) codeLanguageContainer.setLayout(hLayout0) self.temporalButton = QRadioButton('Temporal', self) self.temporalButton.toggled.connect(self.temporalToggled) self.conditionalButton = QRadioButton('Conditional', self) self.conditionalButton.toggled.connect(self.conditionalToggled) radioButtonContainer = QGroupBox() radioButtonContainer.setTitle('Transition Type') vLayout = QVBoxLayout() vLayout.addWidget(self.temporalButton) vLayout.addWidget(self.conditionalButton) radioButtonContainer.setLayout(vLayout) self.transitionTypeCode = QTextEdit() self.transitionTypeCode.setFont(fixedWidthFont) self.transitionGroupBox = QGroupBox() self.transitionGroupBox.setTitle('Temporal (number in ms)') h3Layout = QHBoxLayout() h3Layout.addWidget(self.transitionTypeCode) self.transitionGroupBox.setLayout(h3Layout) typeContainer = QWidget() h2Layout = QHBoxLayout() h2Layout.addWidget(radioButtonContainer) h2Layout.addWidget(self.transitionGroupBox) typeContainer.setLayout(h2Layout) verticalLayout = QVBoxLayout() verticalLayout.addWidget(typeContainer) verticalLayout.addWidget(codeLanguageContainer) verticalLayout.addWidget(self.codeEdit) container = QWidget() hLayout =QHBoxLayout() hLayout.addWidget(self.cancelButton) hLayout.addWidget(self.acceptButton) container.setLayout(hLayout) verticalLayout.addWidget(container) self.setLayout(verticalLayout) if self.transition.getType() == TransitionType.CONDITIONAL: self.conditionalButton.setChecked(True) self.conditionalToggled() elif self.transition.getType() == TransitionType.TEMPORAL: self.temporalButton.setChecked(True) self.temporalToggled() def cancel(self): self.close() def accept(self): type = None typeValue = None if self.temporalButton.isChecked(): type = int(TransitionType.TEMPORAL) typeValue = self.transitionTypeCode.toPlainText() elif self.conditionalButton.isChecked(): type = int(TransitionType.CONDITIONAL) typeValue = self.transitionTypeCode.toPlainText() self.codeChanged.emit(type, typeValue, self.codeEdit.text()) self.close() def temporalToggled(self): if (self.temporalButton.isChecked()): self.transitionGroupBox.setTitle('Temporal (number in ms)') self.transitionTypeCode.setPlainText(str(self.transition.getTemporalTime())) # print('temporal toggled') def conditionalToggled(self): if (self.conditionalButton.isChecked()): self.transitionGroupBox.setTitle('Condition (evaluates to true or false)') self.transitionTypeCode.setPlainText(self.transition.getCondition()) # print('conditional toggled') def pythonClicked(self): fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.language = 'python' def cppClicked(self): fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) lexer = QsciLexerCPP() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.language = 'cpp'
class MainWindow(QMainWindow): def __init__(self): super().__init__(flags=0) self.code = QsciScintilla() # self.code.setTabStopWidth(4) self.code.setTabWidth(4) self.code.setMarginWidth(1, 100) self.code.setMarginLineNumbers(1, True) self.code.setAutoIndent(True) self.font = QFont('Courier New', 18) self.code.setFont(self.font) self.code.setMinimumSize(1024, 768) self.locations = {} self.debug_mode = False self.setCentralWidget(self.code) self.pane_output = QDockWidget('Output', self) self.output = QTextEdit(self.pane_output) self.pane_memory = QDockWidget('Memory', self) self.memory_list = QListWidget(self.pane_memory) self.memory = [0] * 65536 self.setup_menu() self.setup_panes() self.cfg = Config() self.directory = self.cfg.get('directory') self.filename = self.cfg.get('filename') if self.filename: self.open_file(self.filename) self.mega = Mega() self.update_memory_list() self.load_settings() def load_settings(self): geom = self.cfg.get('geometry') if not isinstance(geom, str): self.restoreGeometry(geom) state = self.cfg.get('state') if not isinstance(state, str): self.restoreState(state) def closeEvent(self, e: QCloseEvent) -> None: self.cfg.set('geometry', self.saveGeometry()) self.cfg.set('state', self.saveState()) def setup_panes(self): self.pane_output.setObjectName('Output') self.pane_output.setAllowedAreas(Qt.BottomDockWidgetArea) self.output.setTextInteractionFlags(Qt.TextSelectableByMouse) self.output.setFont(self.font) self.pane_output.setWidget(self.output) self.addDockWidget(Qt.BottomDockWidgetArea, self.pane_output) self.pane_memory.setObjectName('Memory') self.pane_memory.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.pane_memory.setWidget(self.memory_list) self.memory_list.setFont(self.font) self.addDockWidget(Qt.RightDockWidgetArea, self.pane_memory) def setup_menu(self): mb = self.menuBar() m = mb.addMenu('&File') dir_open = QAction('Open &Dir', m) dir_open.triggered.connect(self.on_dir_open) m.addAction(dir_open) file_open = QAction('&Open', m) file_open.triggered.connect(self.on_file_open) file_open.setShortcut('Ctrl+O') m.addAction(file_open) file_save = QAction('&Save', m) file_save.triggered.connect(self.on_file_save) file_save.setShortcut('Ctrl+S') m.addAction(file_save) m = mb.addMenu('&Build') assemble = QAction('&Assemble', m) assemble.triggered.connect(self.on_assemble) assemble.setShortcut('F7') m.addAction(assemble) program = QAction('&Program', m) program.triggered.connect(self.on_program) program.setShortcut('F9') m.addAction(program) m = mb.addMenu('&Debug') start = QAction('&Mode', m) start.triggered.connect(self.on_toggle_debug) start.setShortcut('F5') m.addAction(start) clock = QAction('&Clock', m) clock.triggered.connect(self.on_clock) clock.setShortcut('F11') m.addAction(clock) clock = QAction('&AutoClock', m) clock.triggered.connect(self.on_auto_clock) m.addAction(clock) ram = QAction('&RAM Update', m) ram.triggered.connect(self.on_update_memory) ram.setShortcut('F6') m.addAction(ram) def on_dir_open(self): res = QFileDialog.getExistingDirectory(caption='Select Directory', directory=self.directory) print(res) def open_file(self, filename): try: self.code.setText(open(filename).read()) self.cfg.set('filename', filename) except IOError: QMessageBox.warning(self, title='Error', text=f'Cannot open {filename}') def on_file_open(self): res = QFileDialog.getOpenFileName(caption='Open', filter='*.asm') filename = res[0] if filename: self.open_file(filename) def on_file_save(self): if self.filename: code = self.code.text() with open(self.filename, 'w') as f: f.write(code) def set_output(self, text, default=''): if not text: text = default self.output.setText(text) def on_assemble(self): work_dir = os.path.dirname(self.filename) filename = os.path.basename(self.filename) try: res = subprocess.run(['zasm', filename, '0', '0'], capture_output=True, cwd=work_dir, check=True) self.set_output(res.stdout.decode('utf-8'), 'Done') except subprocess.CalledProcessError: self.set_output('Assembler failed') def on_program(self): bin_name = self.filename.replace('.asm', '.bin') try: data = open(bin_name, 'rb').read() self.mega.write_memory(0, data) except IOError: QMessageBox.warning(parent=self, title='Error', text='Failed to open binary') def on_toggle_debug(self): if self.debug_mode: self.on_stop_debug() else: self.on_start_debug() def on_stop_debug(self): self.debug_mode = False try: self.code.setText(open(self.filename).read()) self.code.setReadOnly(False) except IOError: QMessageBox.warning(parent=self, title="Error", text=f'File "{self.filename}" not found') def on_start_debug(self): self.debug_mode = True lst_name = self.filename.replace('.asm', '.lst') try: listing = open(lst_name).read() self.code.setText(listing) self.code.setReadOnly(True) i = 0 for line in listing.split('\n'): parts = line.split() if parts: address = int(parts[0], 0) self.addr2line[address] = i i += 1 except IOError: QMessageBox.warning(parent=self, title='Error', text='No listing found. Try assemble') def on_clock(self): count = 0 print("------------------------------------------------------") while True: address, data, flags = self.mega.clock_read_bus() print(f'{address:04x}:{data:02x} {flags:02x} {flag_text(flags)}') if (flags & 3) == 0: count += 1 if count >= 2: if address in self.addr2line: y = self.addr2line.get(address) self.code.setSelection(y, 0, y + 1, 0) break def on_auto_clock(self): self.mega.auto_clock() def update_memory_list(self): self.memory_list.clear() for address in range(0, 8192, 16): line = f'{address:04x}' for i in range(16): line = line + f' {self.memory[address + i]:02x}' self.memory_list.addItem(QListWidgetItem(line)) def update_memory(self, address: int, length: int): if address < 0 or (address + length) > len(self.memory): QMessageBox.warning(parent=self, title='Error', text='Invalid memory range') return data = self.mega.read_memory(address, length) self.memory[address:(address + length)] = data self.update_memory_list() def on_update_memory(self): self.update_memory(0, 8192)
color: $text; background-color: rgb(255,255,20); } /* ======================== */ /* MENU==================== */ QMenuBar[aa="bbb"], #xxxx .abcc { background-color: "red"; aaa: 'bbb'; } QMenuBar::item { background: transparent; } QMenuBar::item:selected { background:#8bf; border: 1px solid #8bf; } """.replace("\n", "\r\n") app = QApplication(sys.argv) win = QsciScintilla() win.setText(myCodeSample) l = QsciLexerQSS(win) win.setLexer(l) win.show() QApplication.setStyle(QStyleFactory.create('Fusion')) sys.exit(app.exec_())
class BrowserWindow(QWidget): launcherWindow = None logoPixmap = None def __init__(self, launcherWindow, app): super().__init__() self.app = app self.launcherWindow = launcherWindow self.fontSize = 14 self.fontSizeLarge = 24 self.fontSizeSmall = 10 self.setCursor(AppData.cursors['arrow']) self.initUI() def multiple_replace(self, string, rep_dict): pattern = re.compile("|".join([re.escape(k) for k in rep_dict.keys()]), re.M) return pattern.sub(lambda x: rep_dict[x.group(0)], string) def styleEsc(self, string): return self.multiple_replace(string, { '{': '{{', '}': '}}', '@<': '{', '>@': '}' }) def initUI(self): ## pal = QPalette(); ## pal.setColor(QPalette.Background, Qt.black); ## self.setPalette(pal); self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.styleTemplate = self.styleEsc(""" QWidget{ background-color: black; border-color: red; border-style: solid; border-width: 1px; border-radius: 0px; font: bold @<fontSize>@px; color: red; padding: 0px; font-family: "Candara"; font-size: @<fontSize:d>@px; } QLabel{ font-size: @<fontSizeLarge:d>@px; border-width: 0px; } QTreeView::item:hover { background: black; border: 1px solid red; } QTreeView::item:selected { border: 1px solid red; color: red; } QTreeView::item:selected:active{ background: black; border: 1px solid red; } QTreeView::item:selected:!active { border: 1px solid red; color: red; } QTreeView::branch:has-siblings:!adjoins-item { border-image: url(Gui/stylesheet-vline.png) 0; } QTreeView::branch:has-siblings:adjoins-item { border-image: url(Gui/stylesheet-branch-more.png) 0; } QTreeView::branch:!has-children:!has-siblings:adjoins-item { border-image: url(Gui/stylesheet-branch-end.png) 0; } QTreeView::branch:has-children:!has-siblings:closed, QTreeView::branch:closed:has-children:has-siblings { border-image: none; image: url(Gui/stylesheet-branch-closed.png); } QTreeView::branch:open:has-children:!has-siblings, QTreeView::branch:open:has-children:has-siblings { border-image: none; image: url(Gui/stylesheet-branch-open.png); } QScrollBar:vertical { border: 2px solid red; background: black; width: 40px; margin: 22px 0 22px 0; } QScrollBar::handle:vertical { background: red; min-height: 20px; } QScrollBar::add-line:vertical { border: 2px red; background: black; height: 20px; subcontrol-position: bottom; subcontrol-origin: margin; } QScrollBar::sub-line:vertical { border: 2px red; background: black; height: 20px; subcontrol-position: top; subcontrol-origin: margin; } QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { border: 2px solid black; width: 3px; height: 3px; background: red; } QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { background: none; } """) self.setStyleSheet( self.styleTemplate.format(fontSize=int(self.fontSize), fontSizeLarge=int(self.fontSizeLarge))) #gridWidget = QWidget(self) #self.gridWidget = gridWidget grid = QGridLayout() #treeMooker = QWidget(self) #treeMooker.setStyleSheet("background-color: transparent;") #treeMooker.setAttribute(Qt.WA_TransparentForMouseEvents) #treeMooker.installEventFilter(self) #treeMookerGrid = QGridLayout() #stack = QStackedLayout() #stack.setStackingMode(QStackedLayout.StackAll) logo = QLabel(self) self.logoPixmap = QPixmap("./Project/Media/Gears.png") logo.setPixmap(self.logoPixmap) logo.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) grid.addWidget(logo, 2, 3, 1, 1) self.titleTemplate = self.styleEsc(''' <p align="left"><strong> <span style='font-size:@<fontSizeLarge>@pt; font-weight:600; color:#ff0000;'>GPU Eye And Retina Stimulation </span></strong><span style='font-size:10pt; font-weight:600; color:#aa0000;'>beta test version 0.4</span></p> <table border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td > <p align="left"><span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>László Szécsi</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>Budapest University of Technology and Economics</span></p> </td> </tr> <tr> <td > <p align="left"> <span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Péter Hantz</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>University of Pécs, Medical School</span></p> </td> </tr> <tr> <td > <p align="left"> <span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Ágota Kacsó</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>Budapest University of Technology and Economics</span></p> </td> </tr> <tr> <td > <p align="left"><span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Günther Zeck</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>Natural and Medical Sciences Institute Reutlingen</span></p> </td> </tr> <tr> <td > <p align="left"><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>http://www.gears.vision</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>[email protected]</span></p> </td> </tr> </tbody> </table> ''') self.titleLabel = QLabel( self.titleTemplate.format(fontSize=self.fontSize, fontSizeLarge=self.fontSizeLarge, fontSizeSmall=self.fontSizeSmall)) self.titleLabel.setTextFormat(Qt.RichText) self.titleLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) grid.addWidget(self.titleLabel, 1, 3, 1, 1) self.instructionsTemplate = self.styleEsc(''' <p align="left"><strong> <table border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td > <p align="left"><span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Reset tree</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>press space</span></p> </td> </tr> <tr> <td > <p align="left"><span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Navigate</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>press key for first character</span></p> </td> </tr> <tr> <td > <p align="left"> <span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Change font size</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>ctrl+mouse wheel</span></p> </td> </tr> <tr> <td > <p align="left"><span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Edit or configure</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>right click tree item</span></p> </td> </tr> <tr> <td > <p align="left"><span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>/</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'> @<emptyFolderOp>@ empty folders</span></p> </td> </tr> </tbody> </table> ''') self.instructionsLabel = QLabel( self.instructionsTemplate.format(fontSize=self.fontSize, fontSizeLarge=self.fontSizeLarge, fontSizeSmall=self.fontSizeSmall, emptyFolderOp='show')) self.instructionsLabel.setStyleSheet(''' QLabel{ border-width: 1px; } ''') self.instructionsLabel.setTextFormat(Qt.RichText) self.instructionsLabel.setAlignment(Qt.AlignHCenter) grid.addWidget(self.instructionsLabel, 3, 1, 1, 1) specs = QLabel(gears.getSpecs()) #self.titleLabel.setTextFormat( Qt.RichText ) self.titleLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) specs.setFocusPolicy(Qt.NoFocus) #specsButton.clicked.connect(self.onSpecs) grid.addWidget(specs, 4, 1, 1, 1) quitButton = QPushButton('Quit') quitButton.setFocusPolicy(Qt.NoFocus) quitButton.clicked.connect(self.onQuit) grid.addWidget(quitButton, 4, 3, 1, 1) #settingsButton = QPushButton('Measurement hardware') #settingsButton.setFocusPolicy(Qt.NoFocus) #settingsButton.clicked.connect(self.onSet) #grid.addWidget(settingsButton, 3, 3, 1, 1) tree = BrowserTree(self.launcherWindow, self) tree.setAttribute(Qt.WA_TransparentForMouseEvents, on=False) self.tree = tree tree.setFocusPolicy(Qt.NoFocus) tree.setHeaderHidden(True) tree.setStyleSheet("background-color: black;") item0 = QTreeWidgetItem(tree) item0.setText(0, 'Sequences') itemMap = dict() itemMap["./Project/Sequences"] = item0 rootPath = "./Project/Sequences" emptyDirs = find_empty_dirs(rootPath) for (path, dirs, files) in os.walk(rootPath): for subdir in dirs: if subdir != "__pycache__": fullPath = os.path.join(path, subdir) #if(rootPath == path): # item0 = QTreeWidgetItem(tree) # itemMap[fullPath] = item0 # item0.setText(0, subdir) #else: item1 = QTreeWidgetItem() itemMap[fullPath] = item1 item1.setText(0, subdir) itemMap[path].addChild(item1) if fullPath in emptyDirs: item1.setText( 1, "gears_folder_not_holding_any_sequence_scripts") item1.setHidden(True) for item in files: if item.endswith('.pyx'): #if(rootPath == path): # item0 = QTreeWidgetItem(tree) # itemMap[os.path.join(path, item)] = item0 # item0.setText(0, item) #else: item1 = QTreeWidgetItem() itemMap[os.path.join(path, item)] = item1 item1.setText(0, item) item1.setText(1, "tags spot spatial temporal") itemMap[path].addChild(item1) item0.setExpanded(True) grid.addWidget(tree, 1, 1, 4, 3, Qt.AlignLeft | Qt.AlignTop) #qbtn = QPushButton('Quit', self) #qbtn.clicked.connect(QCoreApplication.instance().quit) #qbtn.resize(qbtn.sizeHint()) #grid.addWidget(qbtn, 8, 9) #treeMooker.setLayout(treeMookerGrid) #gridWidget.setLayout(grid) #stack.addWidget(treeMooker) #stack.addWidget(gridWidget) self.setLayout(grid) self.setWindowTitle('O\u0398\u03a6O') # self.setWindowIcon(QIcon('web.png')) self.showFullScreen() self.setFixedSize(self.size()) self.tree.setCurrentIndex(self.tree.model().index(0, 0)) def keyPressEvent(self, e): if e.key() == Qt.Key_Escape or e.text() == 'q': box = QMessageBox(self) QGuiApplication.setOverrideCursor(AppData.cursors['arrow']) box.setText('Are you sure you want to quit?') box.setWindowTitle('Please confirm!') box.setWindowFlags(Qt.FramelessWindowHint | Qt.Dialog) box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) box.setDefaultButton(QMessageBox.No) if box.exec() == QMessageBox.Yes: self.close() QGuiApplication.restoreOverrideCursor() elif e.key() == Qt.Key_Space or e.key() == Qt.Key_Backspace: self.tree.setCurrentItem(self.tree.topLevelItem(0)) self.tree.collapseAll() self.tree.topLevelItem(0).setExpanded(True) elif e.key() == Qt.Key_Down: ni = self.tree.itemBelow(self.tree.currentItem()) if (ni != None): self.tree.setCurrentItem(ni) elif e.key() == Qt.Key_Up: ni = self.tree.itemAbove(self.tree.currentItem()) if (ni != None): self.tree.setCurrentItem(ni) elif e.key() == Qt.Key_Left: ni = self.tree.currentItem().parent() if (ni != None): self.tree.setCurrentItem(ni) elif e.key() == Qt.Key_Right or e.key() == Qt.Key_Return or e.key( ) == Qt.Key_Enter: ni = self.tree.currentItem().child(0) if (ni != None): self.tree.setCurrentItem(ni) else: self.tree.open(self.tree.currentItem(), False) elif e.key() == Qt.Key_Slash: self.tree.hideEmptyFolders(not self.tree.isHidingEmptyFolders) self.instructionsLabel.setText( self.instructionsTemplate.format( fontSize=int(self.fontSize), fontSizeLarge=int(self.fontSizeLarge), fontSizeSmall=int(self.fontSizeSmall), emptyFolderOp=('show' if self.tree.isHidingEmptyFolders else 'hide'))) #elif e.key()==Qt.Key_0 or e.key()==Qt.Key_1 or e.key()==Qt.Key_2 or e.key()==Qt.Key_3 or e.key()==Qt.Key_4 or e.key()==Qt.Key_5 or e.key()==Qt.Key_6 or e.key()==Qt.Key_7 or e.key()==Qt.Key_8 or e.key()==Qt.Key_9 : else: self.tree.clearSelection() self.tree.keyboardSearch(e.text()) sel = self.tree.selectedItems() if len(sel) > 0: self.tree.onClick(sel[0], 0) def onSpecs(self): box = QMessageBox(self) horizontalSpacer = QSpacerItem(1000, 0, QSizePolicy.Minimum, QSizePolicy.Expanding) box.setText(gears.getSpecs()) box.setWindowTitle('System specs') box.setWindowFlags(Qt.FramelessWindowHint | Qt.Dialog) box.setStandardButtons(QMessageBox.Ok) box.setDefaultButton(QMessageBox.Ok) layout = box.layout() layout.addItem(horizontalSpacer, layout.rowCount(), 0, 1, layout.columnCount()) box.exec() def onQuit(self): box = QMessageBox(self) #box.setCursor(AppData.cursors['arrow']) QGuiApplication.setOverrideCursor(AppData.cursors['arrow']) box.setText('Are you sure you want to quit?') box.setWindowTitle('Please confirm!') box.setWindowFlags(Qt.FramelessWindowHint | Qt.Dialog) box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) box.setDefaultButton(QMessageBox.No) if box.exec() == QMessageBox.Yes: self.close() QGuiApplication.restoreOverrideCursor() def onSet(self): #from subprocess import call #call("notepad ./Project/Sequences/DefaultSequence.py") self.editor = QsciScintilla() # define the font to use font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) # the font metrics here will help # building the margin width later fm = QFontMetrics(font) ## set the default font of the editor ## and take the same font for line numbers self.editor.setFont(font) self.editor.setMarginsFont(font) ## Line numbers # conventionnaly, margin 0 is for line numbers self.editor.setMarginWidth(0, fm.width("00000") + 5) self.editor.setMarginLineNumbers(0, True) ## Edge Mode shows a red vetical bar at 80 chars self.editor.setEdgeMode(QsciScintilla.EdgeLine) self.editor.setEdgeColumn(80) self.editor.setEdgeColor(QColor("#FF0000")) ## Folding visual : we will use boxes self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle) ## Braces matching self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch) ## Editing line color self.editor.setCaretLineVisible(True) self.editor.setCaretLineBackgroundColor(QColor("#CDA869")) ## Margins colors # line numbers margin self.editor.setMarginsBackgroundColor(QColor("#333333")) self.editor.setMarginsForegroundColor(QColor("#CCCCCC")) # folding margin colors (foreground,background) self.editor.setFoldMarginColors(QColor("#99CC66"), QColor("#333300")) ## Choose a lexer lexer = QsciLexerPython() lexer.setDefaultFont(font) api = QsciStrictAPIs(lexer) api.prepare() lexer.setDefaultFont(font) self.editor.setLexer(lexer) self.editor.setMinimumSize(1024, 768) self.editor.show() ## Show this file in the editor text = open("./Project/Sequences/DefaultSequence.py").read() self.editor.setText(text) def wheelEvent(self, event): if self.app.keyboardModifiers() & Qt.ControlModifier: self.fontSize += event.angleDelta().y() / 120 self.fontSizeLarge += event.angleDelta().y() / 120 self.fontSizeSmall += event.angleDelta().y() / 120 self.setStyleSheet( self.styleTemplate.format(fontSize=int(self.fontSize), fontSizeLarge=int( self.fontSizeLarge))) self.titleLabel.setText( self.titleTemplate.format( fontSize=int(self.fontSize), fontSizeLarge=int(self.fontSizeLarge), fontSizeSmall=int(self.fontSizeSmall))) self.instructionsLabel.setText( self.instructionsTemplate.format( fontSize=int(self.fontSize), fontSizeLarge=int(self.fontSizeLarge), fontSizeSmall=int(self.fontSizeSmall), emptyFolderOp=('show' if self.tree.isHidingEmptyFolders else 'hide'))) self.tree.resizeColumnToContents(0) self.updateGeometry() #def eventFilter(self, obj, event): # #if event.type() in [ QEvent.MouseMove, QEvent.MouseButtonPress, QEvent.MouseButtonRelease, QEvent.MouseButtonDblClick]: # self.app.sendEvent(self.gridWidget, event) # return super().eventFilter(obj, event) def sizeHint(self): return self.app.desktop().screenGeometry().size()
def createCodeEditor(initial): editor = QsciScintilla() """ Customization - GENERAL """ # # Disable the lexer editor.setLexer(QsciLexerFortran()) # # Set the encoding to UTF-8 # editor.setUtf8(True) # # Set the tab width to 4 spaces # editor.setTabWidth(2) # # Set the End-Of-Line character to Unix style ('\n') # editor.setEolMode(QsciScintilla.EolUnix) # # Make End-Of-Line characters visible # # editor.setEolVisibility(True) # # Set the zoom factor, the factor is in points. # editor.zoomTo(4) # # """ # Customization - LINE WRAPPING # """ # # Set the text wrapping mode to word wrap # editor.setWrapMode(QsciScintilla.WrapWord) # # Set the text wrapping mode visual indication # editor.setWrapVisualFlags( # QsciScintilla.WrapFlagByText, QsciScintilla.WrapFlagByText # ) # # Set the text wrapping to indent the wrapped lines # editor.setWrapIndentMode(QsciScintilla.WrapIndentSame) # # """ # Customization - EDGE MARKER # """ # # Set the edge marker's position and set it to color the background # # when a line goes over the limit of 50 characters # # editor.setEdgeMode(QsciScintilla.EdgeBackground) # # editor.setEdgeColumn(40) # edge_color = caret_fg_color = QColor("#ff00ff00") # # editor.setEdgeColor(edge_color) # # Add a long line that will display the edge marker coloring # # """ # Customization - INDENTATION # """ # # Set indentation with spaces instead of tabs # # editor.setIndentationsUseTabs(False) # # Set the tab width to 4 spaces # editor.setTabWidth(2) # # Set tab indent mode, see the 3.3.3 chapter in QSciDocs # # for a detailed explanation # # editor.setTabIndents(True) # # Set autoindentation mode to maintain the indentation level of the previous line # # (the editor's lexer HAS to be disabled) # # editor.setAutoIndent(True) # # Make the backspace jump back to the tab width guides instead of deleting # # one character, but only when there are ONLY whitespaces on the left side of the cursor # # editor.setBackspaceUnindents(True) # # Set indentation guides to be visible # # editor.setIndentationGuides(True) # # """ # Customization - CARET (the blinking cursor indicator) # """ # # Set the caret color to red # caret_fg_color = QColor("#ffff0000") # editor.setCaretForegroundColor(caret_fg_color) # # Enable and set the caret line background color to slightly transparent blue # editor.setCaretLineVisible(True) # caret_bg_color = QColor("#1f0000ff") # editor.setCaretLineBackgroundColor(caret_bg_color) # # Set the caret width of 4 pixels # # editor.setCaretWidth(4) # # """ # Customization - AUTOCOMPLETION (Partially usable without a lexer) # """ # # Set the autocompletions to case INsensitive # editor.setAutoCompletionCaseSensitivity(False) # # Set the autocompletion to not replace the word to the right of the cursor # editor.setAutoCompletionReplaceWord(False) # # Set the autocompletion source to be the words in the document # editor.setAutoCompletionSource(QsciScintilla.AcsDocument) # # Set the autocompletion dialog to appear as soon as 1 character is typed # editor.setAutoCompletionThreshold(2) # # """ # Customization - CALL TIPS (Not usable without a lexer) # """ # # # Set the call tips foreground and background color # # calltip_fg_color = QColor("#7f7f0000") # # calltip_bg_color = QColor("#7f0000ff") # # editor.setCallTipsForegroundColor(calltip_fg_color) # # editor.setCallTipsBackgroundColor(calltip_bg_color) # # # Set the call tips to appear above the text # # editor.setCallTipsPosition(QsciScintilla.CallTipsAboveText) # # # Set the call tips to ve displayed without any context # # editor.setCallTipsStyle(QsciScintilla.CallTipsNoContext) # # # Make the call tips visible # # editor.setCallTipsVisible(0) editor.setText(initial) return editor
editor.setText( textwrap.dedent("""\ #include <iostream> using namespace std; void Function0() { cout << "Function0"; } void Function1() { cout << "Function1"; } void Function2() { cout << "Function2"; } void Function3() { cout << "Function3"; } int main(void) { if (1) { if (1) { if (1) { if (1) { int yay; } } } } if (1) { if (1) { if (1) { if (1) { int yay2; } } } } return 0; }\ """))
#!/usr/bin/env python # I failed to install correct versoin of qscintilla using pip - # only `python-qscintilla-qt 2.11.4-1` package from aur worked # correctly from PyQt5.Qsci import QsciScintilla from PyQt5.QtWidgets import QApplication app = QApplication([]) ed = QsciScintilla() ed.setText('insert <-\nsome <-\ntext <-\n') ed.show() # typing should insert in all selections at the same time ed.SendScintilla(ed.SCI_SETADDITIONALSELECTIONTYPING, 1) # do multiple selections offset = ed.positionFromLineIndex(0, 7) # line-index to offset ed.SendScintilla(ed.SCI_SETSELECTION, offset, offset) # using the same offset twice selects no characters, hence a cursor offset = ed.positionFromLineIndex(1, 5) ed.SendScintilla(ed.SCI_ADDSELECTION, offset, offset) offset = ed.positionFromLineIndex(2, 5) ed.SendScintilla(ed.SCI_ADDSELECTION, offset, offset) app.exec_()
class CodeDialog(QDialog): codeChanged = pyqtSignal('QString') def __init__(self, name, currentValue): super(QDialog, self).__init__() self.setWindowTitle(name) self.resize(800, 600) self.codeEdit = QsciScintilla() self.codeEdit.setText(currentValue) fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.codeEdit.setFont(fixedWidthFont) fontmetrics = QFontMetrics(fixedWidthFont) self.codeEdit.setMarginWidth(0, fontmetrics.width("000")) self.codeEdit.setMarginLineNumbers(0, True) self.codeEdit.setMarginsBackgroundColor(QColor("#cccccc")) self.codeEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.codeEdit.setCaretLineVisible(True) self.codeEdit.setCaretLineBackgroundColor(QColor("#ffe4e4")) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.codeEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.codeEdit.setUtf8(True) self.codeEdit.setTabWidth(4) self.codeEdit.setIndentationsUseTabs(True) self.codeEdit.setIndentationGuides(True) self.codeEdit.setTabIndents(True) self.codeEdit.setAutoIndent(True) self.cancelButton = QPushButton('Cancel') self.cancelButton.clicked.connect(self.cancel) self.acceptButton = QPushButton('Accept') self.acceptButton.clicked.connect(self.accept) self.pythonButton = QRadioButton('Python') self.pythonButton.setChecked(True) self.pythonButton.clicked.connect(self.pythonClicked) self.cppButton = QRadioButton('C++') self.cppButton.clicked.connect(self.cppClicked) hLayout0 = QHBoxLayout() hLayout0.addWidget(self.pythonButton) hLayout0.addWidget(self.cppButton) container0 = QWidget() container0.setLayout(hLayout0) verticalLayout = QVBoxLayout() verticalLayout.addWidget(container0) verticalLayout.addWidget(self.codeEdit) container = QWidget() hLayout =QHBoxLayout() hLayout.addWidget(self.cancelButton) hLayout.addWidget(self.acceptButton) container.setLayout(hLayout) verticalLayout.addWidget(container) self.setLayout(verticalLayout) self.language = 'python' def cancel(self): self.close() def accept(self): self.codeChanged.emit(self.codeEdit.text()) self.close() def pythonClicked(self): fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.language = 'python' def cppClicked(self): fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) lexer = QsciLexerCPP() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.language = 'cpp'
class ScriptTab(QWidget,): autocomplete_lst = [] def __init__(self, parent, name, script="", filemodified=0): QWidget.__init__(self) self.parent = parent self.tabWidget = self.parent.ui.tabWidget self.gridlayout = QGridLayout(self) self._dirty = False self.initialize_editor() self.gridlayout.addWidget(self.editor) self.setAcceptDrops(True) self.filename = name self.filemodified = filemodified if self.is_file(): self.title = os.path.basename(name) # if self.equals_saved(): # self.filemodified = os.path.getmtime(self.filename) else: self.filename = "" self.title = name # Show this file in the self.editor self.editor.setText(script) self.clean_txt = self.saved() self.update_dirty() self.editor.keyPressEvent = self.key_press_event @property def scriptRunner(self): return self.parent.controller.scriptRunner def wheelEvent(self, event): if event.modifiers() == Qt.ControlModifier: if event.delta() > 0: self.editor.zoomIn() else: self.editor.zoomOut() return QWidget.wheelEvent(self, event) def initialize_editor(self): self.editor = QsciScintilla() # self.editor.cursorPositionChanged.connect(self.e) # self.editor.copyAvailable.connect(self.e) # self.editor.indicatorClicked.connect(self.e) # self.editor.indicatorReleased.connect(self.e) # self.editor.linesChanged.connect(self.e) # self.editor.marginClicked.connect(self.e) # self.editor.modificationAttempted.connect(self.e) # self.editor.modificationChanged.connect(self.e) # self.editor.selectionChanged.connect(self.e) # self.editor.textChanged.connect(self.e) # self.editor.userListActivated.connect(self.e) if self.editor.__class__.__name__ == "LineTextWidget": return # When using PySide without QSciScintilla # define the font to use font = QFont() font.setFamily("Consolas") font.setFixedPitch(True) font.setPointSize(10) # the font metrics here will help # building the margin width later fm = QFontMetrics(font) # set the default font of the self.editor # and take the same font for line numbers self.editor.setFont(font) self.editor.setMarginsFont(font) # Line numbers # conventionnaly, margin 0 is for line numbers self.editor.setMarginWidth(0, fm.width("00000") + 5) self.editor.setMarginLineNumbers(0, True) self.editor.setTabWidth(4) # Folding visual : we will use boxes self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle) self.editor.setAutoIndent(True) # Braces matching self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch) # Editing line color self.editor.setCaretLineVisible(True) self.editor.setCaretLineBackgroundColor(QColor("#CDA869")) # Margins colors # line numbers margin self.editor.setMarginsBackgroundColor(QColor("#333333")) self.editor.setMarginsForegroundColor(QColor("#CCCCCC")) # folding margin colors (foreground,background) self.editor.setFoldMarginColors(QColor("#99CC66"), QColor("#333300")) # Choose a lexer self.lexer = QsciLexerPython() self.lexer.setDefaultFont(font) # Set the length of the string before the editor tries to autocomplete # In practise this would be higher than 1 # But its set lower here to make the autocompletion more obvious self.editor.setAutoCompletionThreshold(1) # Tell the editor we are using a QsciAPI for the autocompletion self.editor.setAutoCompletionSource(QsciScintilla.AcsAPIs) self.editor.setLexer(self.lexer) self.editor.setCallTipsStyle(QsciScintilla.CallTipsContext) # self.editor.setCallTipsVisible(0) # Create an API for us to populate with our autocomplete terms self.api = QsciAPIs(self.lexer) # Compile the api for use in the lexer self.api.prepare() # def tefocusInEvent(self, event): # self.parent.focusInEvent(event) # return QTextEdit.focusInEvent(self.textEditScript, event) def is_file(self): return os.path.isfile(self.filename) def is_modified(self): if self.is_file(): if self.equals_saved(): self.filemodified = os.path.getmtime(self.filename) return str(os.path.getmtime(self.filename)) != str(self.filemodified) else: return False def saved(self): if self.is_file(): f = open(self.filename) saved = f.read() f.close() return saved.strip() else: return "" def equals_saved(self): curr_lines = self.get_script().strip().splitlines() saved_lines = self.saved().strip().splitlines() if len(curr_lines) != len(saved_lines): return False for cl, sl in zip(curr_lines, saved_lines): if cl.strip() != sl.strip(): return False return True @property def dirty(self): if not self._dirty: self.dirty = self.clean_txt != self.get_script() return self._dirty @dirty.setter def dirty(self, dirty): if dirty is False: self.clean_txt = self.get_script() if self._dirty != dirty: self._dirty = dirty self.filename_changed() def update_dirty(self): return self.dirty def index(self): return self.tabWidget.indexOf(self) def filename_changed(self): index = self.parent.ui.tabWidget.indexOf(self) if self.dirty: self.tabWidget.setTabText(index, "%s*" % self.title) else: self.tabWidget.setTabText(index, self.title) def reload(self): self.set_script(self.parent._load_script(self.filename)) self.filemodified = os.path.getmtime(self.filename) def close(self): while self.dirty is True: # While avoids data loss, in case save operation is aborted if self.filename == "": text = "Save unsaved changes?" else: text = "Save %s?" % self.filename ans = QMessageBox.question(self, 'Save', text, QMessageBox.Yes, QMessageBox.Cancel, QMessageBox.No) if ans == QMessageBox.Cancel: return elif ans == QMessageBox.Yes: self.parent.actionSave(False) elif ans == QMessageBox.No: break self.tabWidget.removeTab(self.index()) def _save(self,): f = open(self.filename, 'w') f.write(self.get_script()) f.close() self.title = os.path.basename(self.filename) self.dirty = False def key_press_event(self, event): self.update_dirty() if self.editor.__class__.__name__ == "LineTextWidget": return self.editor.edit.keyReleaseEvent(event) # When using PySide without QSciScintilla QsciScintilla.keyPressEvent(self.editor, event) linenr, pos_in_line = self.editor.getCursorPosition() line = str(self.editor.text(linenr)[:pos_in_line]) if event.key() == Qt.Key_F1: try: self.parent.show_documentation(getattr(self.scriptRunner, str(self.editor.selectedText()))) except AttributeError: pass if event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return: for tip in self.autocomplete_lst: try: if line.endswith(tip[:tip.index('(') ]): self.editor.insert(tip[tip.index('('):]) parent, residual = self.scriptRunner.split_line(line) self.parent.show_documentation(self.scriptRunner.get_function_dict(parent, residual)[residual]) return except ValueError: pass if event.key() < 100 or event.key() in [Qt.Key_Backspace, Qt.Key_Shift]: linenr, pos_in_line = self.editor.getCursorPosition() line = str(self.editor.text(linenr)[:pos_in_line]) lst = self.scriptRunner.get_autocomplete_list(line) if lst is not None: self.api.clear() list(map(self.api.add, lst)) self.api.prepare() if len(lst) > 0: self.autocomplete_lst = lst self.editor.autoCompleteFromAll() shift_event = QKeyEvent(QEvent.KeyPress, Qt.Key_Shift, Qt.NoModifier) QsciScintilla.keyPressEvent(self.editor, shift_event) # show autocomplete list def set_script(self, script): self.editor.setText(script) def get_script(self): return str(self.editor.text()).replace("\r", "").replace(">>> ", "").replace("\t", " ") def dropHandler(self, dataItemList, ctrl, shift, event): pass
class CustomMainWindow(QMainWindow): def __init__(self): super(CustomMainWindow, self).__init__() # -------------------------------- # # Window setup # # -------------------------------- # # 1. Define the geometry of the main window # ------------------------------------------ self.setGeometry(300, 300, 800, 400) self.setWindowTitle("QScintilla Test") # 2. Create frame and layout # --------------------------- self.__frm = QFrame(self) self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }") self.__lyt = QVBoxLayout() self.__frm.setLayout(self.__lyt) self.setCentralWidget(self.__frm) self.__myFont = QFont() self.__myFont.setPointSize(14) # 3. Place a button # ------------------ self.__btn = QPushButton("Qsci") self.__btn.setFixedWidth(50) self.__btn.setFixedHeight(50) self.__btn.clicked.connect(self.__btn_action) self.__btn.setFont(self.__myFont) self.__lyt.addWidget(self.__btn) # -------------------------------- # # QScintilla editor setup # # -------------------------------- # # ! Make instance of QSciScintilla class! # ---------------------------------------- self.__editor = QsciScintilla() self.__editor.setText("This\n") # Line 1 self.__editor.append("is\n") # Line 2 self.__editor.append("a\n") # Line 3 self.__editor.append("QScintilla\n") # Line 4 self.__editor.append("test\n") # Line 5 self.__editor.append("program\n") # Line 6 self.__editor.append("to\n") # Line 7 self.__editor.append("illustrate\n") # Line 8 self.__editor.append("some\n") # Line 9 self.__editor.append("basic\n") # Line 10 self.__editor.append("functions.") # Line 11 self.__editor.setLexer(None) self.__editor.setUtf8(True) # Set encoding to UTF-8 self.__editor.setFont(self.__myFont) # 1. Text wrapping # ----------------- self.__editor.setWrapMode(QsciScintilla.WrapWord) self.__editor.setWrapVisualFlags(QsciScintilla.WrapFlagByText) self.__editor.setWrapIndentMode(QsciScintilla.WrapIndentIndented) # 2. End-of-line mode # -------------------- self.__editor.setEolMode(QsciScintilla.EolWindows) self.__editor.setEolVisibility(False) # 3. Indentation # --------------- self.__editor.setIndentationsUseTabs(False) self.__editor.setTabWidth(4) self.__editor.setIndentationGuides(True) self.__editor.setTabIndents(True) self.__editor.setAutoIndent(True) # 4. Caret # --------- self.__editor.setCaretForegroundColor(QColor("#ff0000ff")) self.__editor.setCaretLineVisible(True) self.__editor.setCaretLineBackgroundColor(QColor("#1f0000ff")) self.__editor.setCaretWidth(2) # 5. Margins # ----------- # Margin 0 = Line nr margin self.__editor.setMarginType(0, QsciScintilla.NumberMargin) self.__editor.setMarginWidth(0, "0000") self.__editor.setMarginsForegroundColor(QColor("#ff888888")) # Margin 1 = Symbol margin self.__editor.setMarginType(1, QsciScintilla.SymbolMargin) self.__editor.setMarginWidth(1, "00000") sym_0 = QImage("icons/sym_0.png").scaled(QSize(16, 16)) sym_1 = QImage("icons/sym_1.png").scaled(QSize(16, 16)) sym_2 = QImage("icons/sym_2.png").scaled(QSize(16, 16)) sym_3 = QImage("icons/sym_3.png").scaled(QSize(16, 16)) self.__editor.markerDefine(sym_0, 0) self.__editor.markerDefine(sym_1, 1) self.__editor.markerDefine(sym_2, 2) self.__editor.markerDefine(sym_3, 3) self.__editor.setMarginMarkerMask(1, 0b1111) # Display a few symbols, and keep their handles stored handle_01 = self.__editor.markerAdd(0, 0) # Green dot on line 0+1 handle_02 = self.__editor.markerAdd(4, 0) # Green dot on line 4+1 handle_03 = self.__editor.markerAdd(5, 0) # Green dot on line 5+1 handle_04 = self.__editor.markerAdd(8, 3) # Red arrow on line 8+1 handle_05 = self.__editor.markerAdd(9, 2) # Red dot on line 9+1 # ! Add editor to layout ! # ------------------------- self.__lyt.addWidget(self.__editor) self.show() '''''' def __btn_action(self): print("Hello World!") ''''''
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Untitled") icon = os.path.join(BASE_DIR, 'ide/Icon.ico') self.setWindowIcon(QIcon(icon)) self.saveLoad = SaveLoad() self.fileName = None self.setupUI() def setupUI(self): centralWidget = QWidget(self) layout = QHBoxLayout(centralWidget) self.fileSysView = QTreeView(centralWidget) self.setupFileSystemViewer() self.editor = QsciScintilla(centralWidget) self.setupEditor() layout.addWidget(self.fileSysView, 1) layout.addWidget(self.editor, 3) self.setCentralWidget(centralWidget) self.setMinimumSize(700, 500) self.defaultMenuBar = QMenuBar(self) self.setupMenus() self.setMenuBar(self.defaultMenuBar) self.show() def setupEditor(self): self.editor.setFont(QFont("Times New Roman", 12)) self.editor.setMargins(2) self.editor.setMarginType(0, QsciScintilla.NumberMargin) self.editor.setMarginType(1, QsciScintilla.SymbolMargin) self.editor.setMarginWidth(0, "000") self.editor.setMarginWidth(1, "00") self.editor.markerDefine(QsciScintilla.RightTriangle, 1) if system() == "Windows": self.editor.setEolMode(QsciScintilla.EolWindows) elif system() == "Linux": self.editor.setEolMode(QsciScintilla.EolUnix) elif system() == "Mac": self.editor.setEolMode(QsciScintilla.EolMac) else: print("Using Windows EOL") self.editor.setEolMode(QsciScintilla.EolWindows) self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.editor.setIndentationsUseTabs(True) self.editor.setTabWidth(4) self.editor.setIndentationGuides(True) self.editor.setTabIndents(True) self.editor.setAutoIndent(True) self.editor.setCaretForegroundColor(QColor("#ff11214b")) self.editor.setCaretLineVisible(True) self.editor.setCaretLineBackgroundColor(QColor("#1f0000ff")) self.editor.setUtf8(True) self.editor.setMarginSensitivity(1, True) self.editor.marginClicked.connect(self.margin_clicked) self.editor.marginRightClicked.connect(self.margin_right_clicked) self.lexer = QsciLexerPython() self.lexer.setFont(QFont("Times New Roman", 12)) self.editor.setLexer(self.lexer) self.editor.textChanged.connect(self.fileChanged) def setupFileSystemViewer(self): model = QFileSystemModel() model.setRootPath("/") self.fileSysView.setModel(model) self.fileSysView.hideColumn(1) self.fileSysView.hideColumn(2) self.fileSysView.hideColumn(3) self.fileSysView.doubleClicked.connect(self.openFile) def setupMenus(self): fileMenu = QMenu(self.defaultMenuBar) fileMenu.setTitle("File") editMenu = QMenu(self.defaultMenuBar) editMenu.setTitle("Edit") viewMenu = QMenu(self.defaultMenuBar) viewMenu.setTitle("View") runMenu = QMenu(self.defaultMenuBar) runMenu.setTitle("Run") settingsMenu = QMenu(self.defaultMenuBar) settingsMenu.setTitle("Settings") self.actionNew = QAction(self) self.actionNew.setText("New") self.actionNew.setShortcut("Ctrl+N") self.actionOpen = QAction(self) self.actionOpen.setText("Open") self.actionOpen.setShortcut("Ctrl+O") self.actionSave = QAction(self) self.actionSave.setText("Save") self.actionSave.setShortcut("Ctrl+S") self.actionSaveAs = QAction(self) self.actionSaveAs.setText("Save As") self.actionSaveAs.setShortcut("Ctrl+Shift+S") self.actionExit = QAction(self) self.actionExit.setText("Exit") self.actionExit.setShortcut("Alt+X") self.actionUndo = QAction(self) self.actionUndo.setText("Undo") self.actionUndo.setShortcut("Ctrl+Z") self.actionRedo = QAction(self) self.actionRedo.setText("Redo") self.actionRedo.setShortcut("Ctrl+Shift+Z") self.actionSelectAll = QAction(self) self.actionSelectAll.setText("Select all") self.actionSelectAll.setShortcut("Ctrl+A") self.actionCut = QAction(self) self.actionCut.setText("Cut") self.actionCut.setShortcut("Ctrl+X") self.actionCopy = QAction(self) self.actionCopy.setText("Copy") self.actionCopy.setShortcut("Ctrl+C") self.actionPaste = QAction(self) self.actionPaste.setText("Paste") self.actionPaste.setShortcut("Ctrl+V") self.actionFind = QAction(self) self.actionFind.setText("Find") self.actionFind.setShortcut("Ctrl+F") self.actionReplace = QAction(self) self.actionReplace.setText("Replace") self.actionReplace.setShortcut("Ctrl+H") self.actionRun = QAction(self) self.actionRun.setText("Run") self.actionRun.setShortcut("F5") self.actionRunCustom = QAction(self) self.actionRunCustom.setText("Run Customized") self.actionRunCustom.setShortcut("Shift+F5") self.actionShell = QAction(self) self.actionShell.setText("Python shell") self.actionShell.setShortcut("Alt+S") self.actionFont = QAction(self) self.actionFont.setText("Font") self.actionEncoding = QAction(self) self.actionEncoding.setText("Encoding") fileMenu.addAction(self.actionNew) fileMenu.addAction(self.actionOpen) fileMenu.addAction(self.actionSave) fileMenu.addAction(self.actionSaveAs) fileMenu.addSeparator() fileMenu.addAction(self.actionExit) editMenu.addAction(self.actionUndo) editMenu.addAction(self.actionRedo) editMenu.addSeparator() editMenu.addAction(self.actionSelectAll) editMenu.addSeparator() editMenu.addAction(self.actionCut) editMenu.addAction(self.actionCopy) editMenu.addAction(self.actionPaste) viewMenu.addAction(self.actionFind) viewMenu.addAction(self.actionReplace) runMenu.addAction(self.actionRun) runMenu.addAction(self.actionRunCustom) runMenu.addAction(self.actionShell) settingsMenu.addAction(self.actionFont) settingsMenu.addAction(self.actionEncoding) self.defaultMenuBar.addAction(fileMenu.menuAction()) self.defaultMenuBar.addAction(editMenu.menuAction()) self.defaultMenuBar.addAction(viewMenu.menuAction()) self.defaultMenuBar.addAction(runMenu.menuAction()) self.defaultMenuBar.addAction(settingsMenu.menuAction()) self.actionNew.triggered.connect(self.new) self.actionOpen.triggered.connect(self.open) self.actionSave.triggered.connect(self.save) self.actionSaveAs.triggered.connect(self.saveAs) self.actionExit.triggered.connect(self.close) self.actionUndo.triggered.connect(self.editor.undo) self.actionRedo.triggered.connect(self.editor.redo) self.actionSelectAll.triggered.connect( lambda: self.editor.selectAll(True)) self.actionCut.triggered.connect(self.editor.cut) self.actionCopy.triggered.connect(self.editor.copy) self.actionPaste.triggered.connect(self.editor.paste) self.actionFind.triggered.connect(self.find) self.actionReplace.triggered.connect(self.replace) self.actionRun.triggered.connect(self.run) self.actionRunCustom.triggered.connect(self.runCustom) self.actionShell.triggered.connect(self.shell) self.actionFont.triggered.connect(self.Font) def margin_clicked(self, margin_nr, line_nr, state): self.editor.markerAdd(line_nr, margin_nr) def margin_right_clicked(self, margin_nr, line_nr, state): self.editor.markerDelete(line_nr, margin_nr) def new(self): if self.windowTitle().endswith("*"): if (Dialogs().Question( self, "Do you want to save your file?") == "accept"): if self.filename is None: self.saveAs() else: self.save() self.editor.setText("") self.setWindowTitle("Untitled") def open(self): if self.windowTitle().endswith("*"): if (Dialogs().Question( self, "Do you want to save your file?") == "accept"): if self.filename is None: self.saveAs() else: self.save() filename = self.saveLoad.OpenDialog() data = Open(filename) if data is not None: self.editor.setText(data) self.setWindowTitle(filename) self.filename = filename def save(self): if self.filename is None: self.saveAs() else: returnval = Save(self.editor.text(), self.filename) if (returnval): Dialogs().Message(self, "File saved successfully") self.setWindowTitle(self.filename) else: Dialogs().Error(self, "File could not be saved") def saveAs(self): self.filename = self.saveLoad.SaveDialog() returnval = Save(self.editor.text(), self.filename) if (returnval): Dialogs().Message(self, "File saved successfully") self.setWindowTitle(self.filename) else: Dialogs().Error(self, "File could not be saved") def run(self): if self.filename is None: self.saveAs() Runfile(self.filename) def runCustom(self): if self.filename is None: self.saveAs() if self.filename != "": print(len(self.filename)) option, ok = QInputDialog().getText( self, "Customized run", "Enter parameters for sys.argv", QLineEdit.Normal, " ") if ok: Runfile(self.filename, option) def shell(self): Shell() def Font(self): font, ok = QFontDialog.getFont() if ok: self.editor.setFont(font) self.lexer.setFont(font) self.editor.setLexer(self.lexer) def openFile(self, signal): fileName = self.fileSysView.model().filePath(signal) if fileName.endswith("py") or fileName.endswith("pyw"): if self.windowTitle().endswith("*"): if Dialogs().Question( self, "Do you want to save your file?") == "accept": if self.filename is None: self.saveAs() else: self.save() data = Open(fileName) if data is not None: self.editor.setText(data) self.setWindowTitle(fileName) self.filename = fileName def fileChanged(self): title = self.windowTitle() if not (title.endswith("*")): self.setWindowTitle(title + " *") def replace(self): replaceObj = replaceDialog(self, self.editor) def find(self): findObj = findDialog(self, self.editor)
class CustomMainWindow(QMainWindow): def __init__(self): super(CustomMainWindow, self).__init__() # Window setup # -------------- # 1. Define the geometry of the main window self.setGeometry(300, 300, 800, 400) self.setWindowTitle("QScintilla Test") # 2. Create frame and layout self.__frm = QFrame(self) self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }") self.__lyt = QVBoxLayout() self.__frm.setLayout(self.__lyt) self.setCentralWidget(self.__frm) self.__myFont = QFont() self.__myFont.setPointSize(14) # 3. Place a button self.__btn = QPushButton("Qsci") self.__btn.setFixedWidth(50) self.__btn.setFixedHeight(50) self.__btn.clicked.connect(self.__btn_action) self.__btn.setFont(self.__myFont) self.__lyt.addWidget(self.__btn) # QScintilla editor setup # ------------------------ # ! Make instance of QsciScintilla class! self.__editor = QsciScintilla() self.__editor.setText("Hello\n") self.__editor.append("world \n") self.__editor.setLexer(None) self.__editor.setUtf8(True) # Set encoding to UTF-8 self.__editor.setFont(self.__myFont) # Will be overridden by lexer! #simple editor options self.__editor.setEolVisibility(False) #sets the end of each line with an EOL character self.__editor.setIndentationsUseTabs(False) #determines whether indent uses tabs or whitespace char. self.__editor.setTabWidth(4) self.__editor.setIndentationGuides(True) self.__editor.setTabIndents(True) self.__editor.setAutoIndent(True) self.__editor.setCaretForegroundColor(QColor("#ff0000ff")) self.__editor.setCaretLineVisible(True) self.__editor.setCaretLineBackgroundColor(QColor("#1fff0000")) self.__editor.setCaretWidth(5) #Margin SetUp. self.__editor.setMarginType(3, self.__editor.NumberMargin) self.__editor.setMarginsForegroundColor(QColor("#ff888888")) # self.__editor.setMarginType(2, QsciScintilla.TextMargin) # Symbol Margin sym_0 = QImage("icons/sym_0.png").scaled(QSize(16, 16)) sym_1 = QImage("icons/sym_1.png").scaled(QSize(16, 16)) sym_2 = QImage("icons/sym_2.png").scaled(QSize(16, 16)) sym_3 = QImage("icons/sym_3.png").scaled(QSize(16, 16)) sym_4 = self.__editor.Circle self.__editor.markerDefine(sym_0, 0) self.__editor.markerDefine(sym_1, 1) self.__editor.markerDefine(sym_2, 2) self.__editor.markerDefine(sym_3, 3) self.__editor.markerDefine(sym_4, 4) self.__editor.setMarginType(3, self.__editor.SymbolMargin) # self.__editor.setMarginType(2, QsciScintilla.SymbolMarginDefaultBackgroundColor) # self.__editor.setMarginType(3, QsciScintilla.SymbolMarginDefaultForegroundColor) self.__editor.setMarginWidth(1, '00000') self.__editor.setMarginMarkerMask(1, 0b1111) self.__editor.setMarginMarkerMask(2, 0b1111) self.__editor.markerAdd(3, 2) # Display a few symbols, and keep their handles stored self.__editor.markerAdd(0, 0) # Green dot on line 0+1 self.__editor.markerAdd(4, 0) # Green dot on line 4+1 self.__editor.markerAdd(5, 0) # Green dot on line 5+1 self.__editor.markerAdd(8, 3) # Red arrow on line 8+1 self.__editor.markerAdd(9, 2) # Red dot on line 9+1 self.__editor.setFolding(self.__editor.BoxedFoldStyle, 4) self.__editor.SendScintilla(self.__editor.SCI_SETMULTIPLESELECTION, True) self.__editor.SendScintilla(self.__editor.SCI_SETMULTIPASTE, 1) self.__editor.SendScintilla(self.__editor.SCI_SETADDITIONALSELECTIONTYPING, True) self.__editor.SendScintilla(self.__editor.SCI_SETINDENTATIONGUIDES, self.__editor.SC_IV_REAL); self.__editor.SendScintilla(self.__editor.SCI_SETTABWIDTH, 4) # self.__editor.setMarginsBackgroundColor(QColor("#ff0000ff")) self.__editor.setWrapMode(QsciScintilla.WrapWord) self.__editor.setWrapIndentMode(QsciScintilla.WrapIndentIndented) # available wrap modes: # QsciScintilla.WrapNone, WrapWord, WrapCharacter, WrapWhitespace self.__editor.setWrapVisualFlags( QsciScintilla.WrapFlagByText, startFlag=QsciScintilla.WrapFlagByText, indent=4) # setWrapVisualFlags(endFlag, startFlag, indent) # see: readMe self.__editor.setWrapIndentMode(QsciScintilla.WrapIndentIndented) self.__editor.textChanged.connect(self.text_changed) #signal typing # ! Add editor to layout ! self.__lyt.addWidget(self.__editor) self.show() '''''' def __btn_action(self): self.__editor.append('Voila You just clicked the QSci button! \n') print("Hello World!") def text_changed(self): print({self.__editor.text()}) ''''''
import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.Qsci import QsciScintilla, QsciLexerPython if __name__ == "__main__": app = QApplication(sys.argv) font = QFont() font.setFamily('Courier') font.setFixedPitch(True) editor = QsciScintilla() editor.setFont(font) lexer = QsciLexerPython() lexer.setFont(font) editor.setLexer(lexer) editor.show() editor.setText(open(sys.argv[0]).read()) app.exec_()