Esempio n. 1
0
    def initEditor(self):
        editor = QsciScintilla()

        ## define the font to use
        font = QtGui.QFont()
        #font.setFamily("Consolas")
        font.setFixedPitch(True)
        font.setPointSize(9)
        # the font metrics here will help
        # building the margin width later
        fm = QtGui.QFontMetrics(font)

        ## set the default font of the editor
        ## and take the same font for line numbers
        editor.setFont(font)
        editor.setMarginsFont(font)

        ## Line numbers
        # conventionnaly, margin 0 is for line numbers
        editor.setMarginWidth(0, fm.width("0000"))
        editor.setMarginLineNumbers(0, True)

        ## Edge Mode shows a red vetical bar at 80 chars
        editor.setEdgeMode(QsciScintilla.EdgeLine)
        editor.setEdgeColumn(80)
        editor.setEdgeColor(QtGui.QColor("#FF0000"))

        ## Folding visual : we will use boxes
        editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)

        ## Braces matching
        editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        ## Editing line color
        editor.setCaretLineVisible(True)
        #editor.setCaretLineBackgroundColor(QtGui.QColor("#F5F5DC"))

        ## Margins colors
        # line numbers margin
        #editor.setMarginsBackgroundColor(QtGui.QColor("#333333"))
        #editor.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))

        # folding margin colors (foreground,background)
        #editor.setFoldMarginColors(QtGui.QColor("#99CC66"),QtGui.QColor("#333300"))

        ## Choose a lexer
        lexer = QsciLexerPython()
        lexer.setDefaultFont(font)
        editor.setLexer(lexer)

        ## Render on screen
        #editor.show()

        ## Show this file in the editor
        #editor.setText(open("examples\charriot_obj.txt").read())

        # Show all the methods of the editor
        #methods = sorted(QsciScintilla.__dict__.keys())
        #for m in methods :
        #    print m
        #editor.setWidth(400)

        editor.setEolMode(QsciScintilla.EolUnix)
        return editor
Esempio n. 2
0
class TakeNote(object):
    def setupUi(self):

############# CREATING MENU START ####################
        self.actionNew = QtGui.QAction('New', self)
        self.actionNew.setShortcut('Ctrl+N')
        self.actionNew.setStatusTip('Create new file')

        self.actionOpen = QtGui.QAction('Open', self)
        self.actionOpen.setShortcut('Ctrl+O')
        self.actionOpen.setStatusTip('Open a file')

        closeAction = QtGui.QAction('Close', self)
        closeAction.setShortcut('Ctrl+Q')
        closeAction.setStatusTip('Close')
        closeAction.triggered.connect(self.close)

        self.wordWrapModeAction = QtGui.QAction('Word wrap', self, checkable=True)
        self.showLineNumbersAction = QtGui.QAction('Show line numbers', self, checkable=True)

        self.editUndoAction = QtGui.QAction('Undo', self)
        self.editUndoAction.setShortcut('Ctrl+Z')
        self.editRedoAction = QtGui.QAction('Redo', self)
        self.editRedoAction.setShortcut('Ctrl+Y')

        self.treeAddNodeAction = QtGui.QAction('Add Node', self)
        self.treeAddNodeAction.setShortcut('Ctrl+T')
        self.treeAddSubNodeAction = QtGui.QAction('Add Subode', self)
        self.treeAddSubNodeAction.setShortcut('Ctrl+Shift+T')

        self.searchAction = QtGui.QAction('Find', self)
        self.searchAction.setShortcut('Ctrl+F')
        self.treeAddNodeAction.setShortcut('Ctrl+T')

        self.aboutAction = QtGui.QAction('About', self)

        menubar = self.menuBar()

        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(self.actionNew)
        fileMenu.addAction(self.actionOpen)
        fileMenu.addAction(closeAction)

        editMenu = menubar.addMenu('&Edit')
        editMenu.addAction(self.editUndoAction)
        editMenu.addAction(self.editRedoAction)

        self.viewMenu = menubar.addMenu('&Search')
        self.viewMenu.addAction(self.searchAction)

        self.viewMenu = menubar.addMenu('&View')
        self.viewMenu.addAction(self.wordWrapModeAction)
        self.viewMenu.addAction(self.showLineNumbersAction)

        treeMenu = menubar.addMenu('&Tree')
        treeMenu.addAction(self.treeAddNodeAction)
        treeMenu.addAction(self.treeAddSubNodeAction)

        helpMenu = menubar.addMenu('&Help')
        helpMenu.addAction(self.aboutAction)
############# CREATING MENU END ####################

############# CREATING WIDGETS START ####################
        #self.resize(800, 600)
        self.splitter = QtGui.QSplitter()
        self.setCentralWidget(self.splitter)
        self.vbox = QtGui.QVBoxLayout(self.splitter)

        ### CREATE TREE WIDGET START ###
        self.treeWidget = QtGui.QTreeWidget(self)
        self.treeWidget.headerItem().setText(0, "Tree")
        self.vbox.addWidget(self.treeWidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(25)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.treeWidget.sizePolicy().hasHeightForWidth())
        self.treeWidget.setSizePolicy(sizePolicy)
        treeFont = QtGui.QFont()
        treeFont.setPointSize(10)
        self.treeWidget.setFont(treeFont)
        ### CREATE TREE WIDGET STOP ###

        ### CREATE TEXT EDIT START ###
        self.textEdit = QsciScintilla(self)
        self.vbox.addWidget(self.textEdit)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(60)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.textEdit.sizePolicy().hasHeightForWidth())
        self.textEdit.setSizePolicy(sizePolicy)

        self.textEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 1)
        self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETADDITIONALSELECTIONTYPING, True)
        self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETMULTIPLESELECTION, True)
        self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETCARETLINEBACK, True)
        self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETCARETLINEVISIBLE, True)
        self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETCARETSTYLE, 1)
        self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETCARETWIDTH, 3)
        self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETMULTIPASTE, 1)
        #self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETSELECTIONMODE, 3)

        # Current line visible with special background color
        self.textEdit.setCaretLineVisible(True)
        self.textEdit.setCaretLineBackgroundColor(QtGui.QColor("#F5F5DC"))

        self.setWindowTitle('TakeNote')
############# CREATING WIDGETS STOP ####################
Esempio n. 3
0
File: test.py Progetto: Neq/Swym
    editor.setMarginWidth(0, fm.width( "00000" ) + 5)
    editor.setMarginLineNumbers(0, True)

    ## Edge Mode shows a red vetical bar at 80 chars
    editor.setEdgeMode(QsciScintilla.EdgeLine)
    editor.setEdgeColumn(80)
    editor.setEdgeColor(QtGui.QColor("#FF0000"))

    ## Folding visual : we will use boxes
    editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)

    ## Braces matching
    editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)

    ## Editing line color
    editor.setCaretLineVisible(True)
    editor.setCaretLineBackgroundColor(QtGui.QColor("#CDA869"))

    ## Margins colors
    # line numbers margin
    editor.setMarginsBackgroundColor(QtGui.QColor("#333333"))
    editor.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))

    # folding margin colors (foreground,background)
    editor.setFoldMarginColors(QtGui.QColor("#99CC66"),QtGui.QColor("#333300"))

    ## Choose a lexer
    lexer = QsciLexerPython()
    lexer.setDefaultFont(font)
    editor.setLexer(lexer)
Esempio n. 4
0
class ScriptManager(MDialog):
    def __init__(self, _parent):
        MDialog.__init__(self, _parent)
        from PyQt4.Qsci import QsciScintilla, QsciLexerPython, QsciAPIs

        if isActivePyKDE4:
            self.setButtons(MDialog.NoDefault)
        self.sciCommand = QsciScintilla()
        self.sciCommand.setUtf8(True)
        self.sciCommand.setAutoIndent(True)
        self.sciCommand.setIndentationGuides(True)
        self.sciCommand.setIndentationsUseTabs(True)
        self.sciCommand.setCaretLineVisible(True)
        self.sciCommand.setAutoCompletionThreshold(2)
        self.sciCommand.setAutoCompletionSource(QsciScintilla.AcsDocument)
        self.sciCommand.setLexer(QsciLexerPython(self))
        self.sciCommand.setMarginLineNumbers(1, True)
        self.sciCommand.setMarginWidth(1, '0000')
        self.sciCommand.setEolMode(QsciScintilla.EolUnix)
        self.sciCommand.setWrapMode(QsciScintilla.WrapWord)
        lblScriptList = MLabel(translate("ScriptManager", "Script List : "))
        self.currentScriptFileName = None
        self.lwScriptList = Options.MyListWidget(self, [], _currentRowChanged=self.getFromScriptList)
        self.refreshScriptList()
        pbtnCreate = MPushButton(translate("ScriptManager", "Create"))
        pbtnDelete = MPushButton(translate("ScriptManager", "Delete"))
        pbtnSave = MPushButton(translate("ScriptManager", "Save"))
        pbtnScriptManagerAndClose = MPushButton(translate("ScriptManager", "Run And Close"))
        pbtnScriptManager = MPushButton(translate("ScriptManager", "Run"))
        pbtnClose = MPushButton(translate("ScriptManager", "Close"))
        pbtnClear = MPushButton(translate("ScriptManager", "Clear"))
        self.cckbIsAutoSaveScripts = Options.MyCheckBox(self, translate("ScriptManager", "Auto Save"), 2,
                                                        "isAutoSaveScripts")
        self.connect(pbtnCreate, SIGNAL("clicked()"), self.create)
        self.connect(pbtnDelete, SIGNAL("clicked()"), self.delete)
        self.connect(pbtnSave, SIGNAL("clicked()"), self.save)
        self.connect(pbtnScriptManagerAndClose, SIGNAL("clicked()"), self.runScriptAndClose)
        self.connect(pbtnScriptManager, SIGNAL("clicked()"), self.runScript)
        self.connect(pbtnClose, SIGNAL("clicked()"), self.close)
        self.connect(pbtnClear, SIGNAL("clicked()"), self.clear)
        pnlMain = MWidget(self)
        vblMain = MVBoxLayout(pnlMain)
        vbox = MVBoxLayout()
        vbox.addWidget(lblScriptList)
        vbox.addWidget(self.lwScriptList)
        hbox2 = MHBoxLayout()
        hbox2.addWidget(pbtnCreate)
        hbox2.addWidget(pbtnDelete)
        vbox.addLayout(hbox2)
        hbox0 = MHBoxLayout()
        hbox0.addLayout(vbox)
        hbox0.addWidget(self.sciCommand)
        hbox1 = MHBoxLayout()
        hbox1.addWidget(self.cckbIsAutoSaveScripts)
        hbox1.addStretch(1)
        hbox1.addWidget(pbtnClear, 1)
        hbox1.addWidget(pbtnSave, 1)
        hbox1.addWidget(pbtnScriptManager, 1)
        hbox1.addWidget(pbtnScriptManagerAndClose, 1)
        hbox1.addWidget(pbtnClose, 1)
        vblMain.addLayout(hbox0)
        vblMain.addLayout(hbox1)
        if isActivePyKDE4:
            self.setMainWidget(pnlMain)
        else:
            self.setLayout(vblMain)
        self.setWindowTitle(translate("ScriptManager", "Script Manager"))
        self.setWindowIcon(MIcon("Images:scriptManager.png"))
        self.lwScriptList.setMaximumWidth(150)
        self.setMinimumWidth(650)
        self.setMinimumHeight(450)
        self.show()

    def closeEvent(self, _event):
        if self.checkForSave() is False:
            _event.ignore()

    @staticmethod
    def checkScriptManager(_isAlertIfNotAvailable=True):
        try:
            from PyQt4.Qsci import QsciScintilla

            return True
        except:
            if _isAlertIfNotAvailable:
                Dialogs.showError(translate("MenuBar", "Qsci Is Not Installed"),
                                  translate("MenuBar",
                                            "Qsci is not installed on your systems.<br>Please install Qsci on your system and try again."))
            return False

    def getFromScriptList(self, _index=None):
        try:
            if self.checkForSave():
                self.currentScriptFileName = self.scriptList[self.lwScriptList.currentRow()]
                codes = Scripts.getScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
                self.sciCommand.setText(str(codes))
        except:
            ReportBug.ReportBug()

    def runScriptAndClose(self):
        try:
            if self.runScript():
                self.close()
        except:
            ReportBug.ReportBug()

    def runScript(self):
        try:
            return Scripts.runScript(str(self.sciCommand.text()))
        except:
            ReportBug.ReportBug()

    def checkForSave(self):
        try:
            if self.currentScriptFileName is not None:
                if fu.isFile(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName)):
                    codes = Scripts.getScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
                    if str(codes) != str(self.sciCommand.text()):
                        if self.cckbIsAutoSaveScripts.checkState() == Mt.Checked:
                            self.save()
                        else:
                            answer = Dialogs.ask(translate("ScriptManager", "Do You Wish To Save Your Codes?"),
                                                 translate("ScriptManager",
                                                           "Do you wish to save your codes so that you can continue later?"),
                                                 True)
                            if answer == Dialogs.Yes:
                                self.save()
                            elif answer == Dialogs.Cancel:
                                return False
            return True
        except:
            ReportBug.ReportBug()

    def save(self):
        try:
            codes = Scripts.getScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
            Scripts.saveScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName),
                               str(self.sciCommand.text()))
        except:
            ReportBug.ReportBug()

    def clear(self):
        try:
            answer = Dialogs.ask(translate("ScriptManager", "Your Codes Will Be Deleted!.."),
                                 translate("ScriptManager",
                                           "Your codes will be deleted and the default codes will be installed. Do you wish to clear the current codes?"))
            if answer == Dialogs.Yes:
                Scripts.clearScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
        except:
            ReportBug.ReportBug()

    def delete(self):
        try:
            answer = Dialogs.ask(translate("ScriptManager", "Your Script Will Be Deleted!.."),
                                 translate("ScriptManager",
                                           "Your script will be deleted. Are you sure you want to delete current script?"))
            if answer == Dialogs.Yes:
                fu.removeFile(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
                self.refreshScriptList()
        except:
            ReportBug.ReportBug()

    def create(self):
        try:
            newScriptFileName = Scripts.createNewScript()
            self.refreshScriptList()
            self.lwScriptList.setCurrentRow(self.scriptList.index(newScriptFileName))
        except:
            ReportBug.ReportBug()

    def refreshScriptList(self):
        try:
            self.scriptList = Scripts.getScriptList()
            self.lwScriptList.refresh(self.scriptList)
            scriptFileName = None
            if len(self.scriptList) > 0:
                scriptFileName = self.scriptList[self.lwScriptList.currentRow()]
            self.currentScriptFileName = scriptFileName
        except:
            ReportBug.ReportBug()
Esempio n. 5
0
  def initEditor(self):
    editor = QsciScintilla()

    ## define the font to use
    font = QtGui.QFont()
    #font.setFamily("Consolas")
    font.setFixedPitch(True)
    font.setPointSize(9)
    # the font metrics here will help
    # building the margin width later
    fm = QtGui.QFontMetrics(font)

    ## set the default font of the editor
    ## and take the same font for line numbers
    editor.setFont(font)
    editor.setMarginsFont(font)

    ## Line numbers
    # conventionnaly, margin 0 is for line numbers
    editor.setMarginWidth(0, fm.width( "0000"))
    editor.setMarginLineNumbers(0, True)

    ## Edge Mode shows a red vetical bar at 80 chars
    editor.setEdgeMode(QsciScintilla.EdgeLine)
    editor.setEdgeColumn(80)
    editor.setEdgeColor(QtGui.QColor("#FF0000"))

    ## Folding visual : we will use boxes
    editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)

    ## Braces matching
    editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)

    ## Editing line color
    editor.setCaretLineVisible(True)
    #editor.setCaretLineBackgroundColor(QtGui.QColor("#F5F5DC"))

    ## Margins colors
    # line numbers margin
    #editor.setMarginsBackgroundColor(QtGui.QColor("#333333"))
    #editor.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))

    # folding margin colors (foreground,background)
    #editor.setFoldMarginColors(QtGui.QColor("#99CC66"),QtGui.QColor("#333300"))

    ## Choose a lexer
    lexer = QsciLexerPython()
    lexer.setDefaultFont(font)
    editor.setLexer(lexer)

    ## Render on screen
    #editor.show()

    ## Show this file in the editor
    #editor.setText(open("examples\charriot_obj.txt").read())
    
    # Show all the methods of the editor
    #methods = sorted(QsciScintilla.__dict__.keys())
    #for m in methods :
    #    print m
    #editor.setWidth(400)
    
    editor.setEolMode(QsciScintilla.EolUnix)
    return editor
Esempio n. 6
0
class MainClass(QtGui.QMainWindow,Ui_MainWindow,QsciScintilla):
	def __init__(self,parent=None):
		super(MainClass, self).__init__(parent)
		self.setupUi(self)
		self.setAcceptDrops(True)#拖拽
		self.setWindowIcon(QtGui.QIcon('image/Raymond_logo.png'))
		# self.setWindowTitle(u"Raymond")
		self.dataBaseName="RaymondText.db"
		self.newFile(0)
		self.setTextEdit()
		#所有信号与槽都放在这里
		self.signalsAndSlots()

	#----------所有信号与槽都放在这里----------#
	def signalsAndSlots(self):
		self.file_newFile.triggered.connect(self.newFile)
		self.file_openFile.triggered.connect(self.openFile)
		self.file_save.triggered.connect(self.saveFile)
		self.connect(self.tabWidget, QtCore.SIGNAL("tabCloseRequested(int)"),self.closeTab)
		self.connect(self.tabWidget, QtCore.SIGNAL("currentChanged(int)"),self.getTabData,)
		



		# self.connect(self.file_newFile, QtCore.SIGNAL('clicked()'), self.newFile)
	#----------end 所有信号与槽都放在这里----------#
	#拖拽处理函数
	def dragEnterEvent(self, event):
		if event.mimeData().hasUrls():
			event.acceptProposedAction()
			# for url in event.mimeData().urls():
				#url=str(url.toLocalFile()).decode('UTF-8').encode('GBK')
		else:
			super(MainClass, self).dragEnterEvent(event)

	def dragMoveEvent(self, event):
		super(MainClass, self).dragMoveEvent(event)
		
	#拖拽释放处理函数
	def dropEvent(self, event):
		if event.mimeData().hasUrls():
			for url in event.mimeData().urls():
				file=str(url.toLocalFile()).decode('UTF-8')
				self.newFile(file)
		else:
			super(MainClass,self).dropEvent(event)

#==========文件菜单中所有功能==========#
	#----------新建文件----------#
	def newFile(self,file):
		# self.tabWidget.setTabBar(HorizontalTabBar())
		#获取QtabBar id信号槽
		self.NewTab = QtGui.QWidget()
		#显示右键菜单
		self.NewTab.setContextMenuPolicy(3)
		self.NewTab.customContextMenuRequested.connect(self.TabRightMenu)
		self.loxLayout = QtGui.QVBoxLayout(self.NewTab)
		self.loxLayout.setContentsMargins(0, 0, 0, 0)
		self.textEdit = QsciScintilla(self.NewTab)
		self.textEdit.setToolTip(_fromUtf8(""))
		self.textEdit.setWhatsThis(_fromUtf8(""))
		if file:
			self.loxLayout.addWidget(self.textEdit)
			self.tabWidget.addTab(self.NewTab, _fromUtf8(""))
			self.textEdit.setText(open(file,'r').read())
			#获取文件名称
			file_name = os.path.basename(file)
			self.tabWidget.setTabText(self.tabWidget.indexOf(self.NewTab), _translate("MainWindow", file_name, None))
			self.setWindowTitle(file+"  - Raymond Text")
		else:
			self.loxLayout.addWidget(self.textEdit)
			self.tabWidget.addTab(self.NewTab, _fromUtf8(""))
			self.tabWidget.setTabText(self.tabWidget.indexOf(self.NewTab), _translate("MainWindow", "新建文件", None))
			self.setWindowTitle(u"Raymond Text")
		# self.tabWidget.setStatusTip(u'行 113, 列 55')
		self.tabWidget.setCurrentIndex(self.tabWidget.currentIndex()+1)
		self.setTextEdit()
	#----------end 新建文件----------#
	#----------打开文件----------#
	def openFile(self):
		file_path =  QtGui.QFileDialog.getOpenFileName(self,u'打开文件',"" ,u"All Files(*.*);;纯文本 (*.txt)")
		self.setWindowTitle(file_path+"  - Raymond Text")
		self.NewTab = QtGui.QWidget()
		#显示右键菜单
		self.NewTab.customContextMenuRequested.connect(self.TabRightMenu)
		self.loxLayout = QtGui.QVBoxLayout(self.NewTab)
		self.loxLayout.setContentsMargins(0, 0, 0, 0)
		self.textEdit = QsciScintilla(self.NewTab)
		self.textEdit.setToolTip(_fromUtf8(""))
		self.textEdit.setWhatsThis(_fromUtf8(""))
		if file_path:
			self.loxLayout.addWidget(self.textEdit)
			self.tabWidget.addTab(self.NewTab, _fromUtf8(""))
			self.textEdit.setText(open(file_path,'r').read())
			#获取文件名称
			file_name=os.path.basename(str(file_path))
			con=connect(self.dataBaseName)
			cur=con.cursor()
			res=(file_name,str(file_path),0,0)
			cur.execute('insert into grouping_data (name,address,groupid,iconPath) values (?,?,?,?)',res)
			con.commit()
			con.close()
			self.tabWidget.setTabText(self.tabWidget.indexOf(self.NewTab), _translate("MainWindow", file_name, None))
			self.tabWidget.setCurrentIndex(self.tabWidget.currentIndex()+1)
			self.setTextEdit()
		
	#----------end 打开文件----------#

	#----------保存文件----------#
	def saveFile(self):
		#获取空口标题
		# print self.windowTitle()
		print self.textEdit.toPlainText()
	#----------end 保存文件----------#
	#----------另存为文件----------#
	def saveAsFile(self):
		file_path =  QtGui.QFileDialog.getSaveFileName(self,u'另存为',"" ,u"All Files(*.*);;纯文本 (*.txt)")
		if file_path:
			fp = open(file_path,"w")     #直接打开一个文件,如果文件不存在则创建文件
			for row in cur:
				data="名称:"+row[1]+"      密码:"+row[2]+"\n"
				print data
				fp.writelines(data)
			fp.close()
	#----------end 另存为文件----------#



#==========end 文件菜单中所有功能==========#

#==========编辑菜单中所有功能==========#
#==========end 编辑菜单中所有功能==========#
	#----------------------杂项.功能--------------------#
	#设置textEdit字体,行号,颜色
	def setTextEdit(self):
		# 设置默认字体
		font = QtGui.QFont()
		font.setFamily('Courier')
		font.setFixedPitch(True)
		font.setPointSize(12)
		self.textEdit.setFont(font)
		self.textEdit.setMarginsFont(font)
		# Margin 0用于行号
		fontmetrics = QtGui.QFontMetrics(font)
		# self.textEdit.setMarginsFont(font)
		# 行号宽度
		# self.textEdit.setMarginWidth(0, fontmetrics.width("00000") + 6)
		self.textEdit.setMarginWidth(0, 60)
		# self.textEdit.setMarginLineNumbers(0, True)
		# 行号背景色
		self.textEdit.setMarginsBackgroundColor(QtGui.QColor("#C7EDCC"))
		# 行号字体颜色
		self.textEdit.setMarginsForegroundColor(QtGui.QColor("#000000"))
		# 高亮当前行与特殊的背景颜色
		self.textEdit.setCaretLineVisible(True)
		self.textEdit.setCaretLineBackgroundColor(QtGui.QColor("#C7EDCC"))
		#光标颜色
		self.textEdit.setCaretForegroundColor(QtGui.QColor("white"))
		#选择字体的背景颜色
		self.textEdit.setSelectionBackgroundColor(QtGui.QColor("#606060"))
		#选择字体的颜色
		self.textEdit.setSelectionForegroundColor(QtGui.QColor("#FFFFFF"))
		#折叠边缘
		self.textEdit.setFolding(QsciScintilla.PlainFoldStyle)
		self.textEdit.setMarginWidth(2,12)
		#括号匹配
		self.textEdit.setBraceMatching(QsciScintilla.StrictBraceMatch)


		#不要看到所有的水平滚动条
		#在这里使用原始消息给Scintilla(所有消息都记录
		#在这里#这里:http://www.scintilla.org/ScintillaDoc.html)
		self.textEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR,0)

	#删除TabWidget中的tab
	def closeTab(self,tabId):
		#关闭置顶信号槽  
		self.tabWidget.removeTab(tabId)
	#获取tab中的数据
	def getTabData(self,tabId):
		if self.tabWidget.tabText(tabId)==u"新建文件":
			self.setWindowTitle(u"新建文件  - Raymond Text")
		else:
			con=connect(self.dataBaseName)
			cur=con.cursor()
			cur.execute('select * from grouping_data where name="%s"'%self.tabWidget.tabText(tabId))
			row=cur.fetchall()
			self.setWindowTitle(row[0][2]+"  - Raymond Text")
			con.commit()
			con.close()
	#tab右键菜单
	def TabRightMenu(self,id):
		self.popMenu = QtGui.QMenu()
		self.popMenu.setStyleSheet("QMenu{background:#fff;border:1px solid #C4C4C4;}QMenu:item{padding:6px 70px 6px 30px;}QMenu:item:selected:enabled{background:#EAEAEA;color:#000}QMenu:item:selected:!enabled{background:transparent;}QMenu:separator{margin:1px 1px 1px 1px;}" )
		self.rc_close = self.popMenu.addAction(u'关闭')
		self.rc_close_other = self.popMenu.addAction(u'关闭其它')
		self.rc_close_right_label = self.popMenu.addAction(u'关闭右侧标签')
		self.rc_new_file = self.popMenu.addAction(u'新建文件')
		self.rc_open_file = self.popMenu.addAction(u'打开文件')
		self.popMenu.move(QtGui.QCursor.pos())
		self.popMenu.show()
		
		self.rc_close.triggered.connect(self.addItem)
		self.rc_close_other.triggered.connect(self.addItem)
		self.rc_close_right_label.triggered.connect(self.addItem)
		self.rc_new_file.triggered.connect(self.addItem)
		self.rc_open_file.triggered.connect(self.addItem)
	def addItem(self):
		print "rc"
Esempio n. 7
0
class Ui_py_de(object):
    def setupUi(self, py_de):
        self.printer = QPrinter()
        self.imagesDir = "images/"

        ####################################
        ## Set up our initial window object
        ####################################

        py_de.setObjectName("py_de")
        py_de.resize(QtCore.QSize(QtCore.QRect(0, 0, 800, 570).size()).expandedTo(py_de.minimumSizeHint()))

        self.centralwidget = QtGui.QTabWidget(py_de)
        self.centralwidget.setObjectName("centralwidget")

        self.centralwidget.setGeometry(QtCore.QRect(50,50,200,200))

	    ####################################
       	## Set up tabs
       	####################################

        self.tab = QtGui.QWidget()
        self.tab.setObjectName("tab")

        self.tablayout = QtGui.QGridLayout(self.tab)

	    ####################################
        ## The actual text box.
        ####################################

        self.textEdit = QsciScintilla(self.tab)

        #####################################
        ### Set the syntax highlighting.
        #####################################

        ## define the font to use
        self.font = QtGui.QFont()
        self.font.setFamily("Consolas")
        self.font.setFixedPitch(True)
        self.font.setPointSize(10)
        # the font metrics here will help
        # building the margin width later
        self.fm = QtGui.QFontMetrics(self.font)

        ## set the default font of the editor
        ## and take the same font for line numbers
        self.textEdit.setFont(self.font)
        self.textEdit.setMarginsFont(self.font)

        ## Line numbers
        # conventionaly, margin 0 is for line numbers
        self.textEdit.setMarginWidth(0, self.fm.width( "00000" ) + 5)
        self.textEdit.setMarginLineNumbers(0, True)

        ## Edge Mode shows a red vertical bar at 80 chars
        self.textEdit.setEdgeMode(QsciScintilla.EdgeLine)
        self.textEdit.setEdgeColumn(80)
        self.textEdit.setEdgeColor(QtGui.QColor("#FF0000"))

        ## Folding visual : we will use boxes
        self.textEdit.setFolding(QsciScintilla.BoxedTreeFoldStyle)

        ## Braces matching
        self.textEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        ## Editing line color
        self.textEdit.setCaretLineVisible(True)
        self.textEdit.setCaretLineBackgroundColor(QtGui.QColor("#CDA869"))

        ## Margins colors
        # line numbers margin
        self.textEdit.setMarginsBackgroundColor(QtGui.QColor("#333333"))
        self.textEdit.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))

        # folding margin colors (foreground,background)
        self.textEdit.setFoldMarginColors(QtGui.QColor("#99CC66"),QtGui.QColor("#333300"))

        ## Choose a lexer
        lexer = QsciLexerPython()
        lexer.setDefaultFont(self.font)
        self.textEdit.setLexer(lexer)

        ## Render on screen
        self.textEdit.show()

        ## Show this file in the self.textEdit

        #####################################
        ## end of syntax highlighting.
        #####################################

	    ####################################
        ## Set up the sizes of everything
        ####################################

        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(1),QtGui.QSizePolicy.Policy(1))
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.textEdit.sizePolicy().hasHeightForWidth())
        self.textEdit.setSizePolicy(sizePolicy)
        self.textEdit.setObjectName("textEdit")

        self.tablayout.addWidget(self.textEdit, 0, 0, 1, 1)

        self.centralwidget.addTab(self.tab,"")
        self.centralwidget.setCurrentIndex(0)

        py_de.setCentralWidget(self.centralwidget)

        self.createMenus(py_de)
        self.createActions(py_de)
        self.createToolBar(py_de)

        self.retranslateUi(py_de)

        #self.createTab(py_de)

        conn = QtCore.QObject.connect
        conn(self.actionNewTemplate,QtCore.SIGNAL("activated()"),self.newTemplate)
        conn(self.actionClose,QtCore.SIGNAL("triggered()"),self.closeTab)
        conn(self.actionQuit,QtCore.SIGNAL("activated()"),py_de.close)
        conn(self.actionOpen,QtCore.SIGNAL("activated()"),self.openFile)
        conn(self.actionPrint,QtCore.SIGNAL("activated()"),self.printFile)
        conn(self.actionSave,QtCore.SIGNAL("activated()"),self.saveFile)
        conn(self.actionSave_As,QtCore.SIGNAL("activated()"),self.saveAsFile)
        conn(self.actionSelect_All,QtCore.SIGNAL("activated()"),self.textEdit.selectAll)
        conn(self.actionGoToLine,QtCore.SIGNAL("activated()"),self.goToLine)
        conn(self.actionCopy,QtCore.SIGNAL("activated()"),self.textEdit.copy)
        conn(self.actionCut,QtCore.SIGNAL("activated()"),self.textEdit.cut)
        conn(self.actionPaste,QtCore.SIGNAL("activated()"),self.textEdit.paste)
        conn(self.actionPython_File,QtCore.SIGNAL("activated()"),self.newPythonFile)
        conn(self.actionC,QtCore.SIGNAL("activated()"),self.newCFile)
        conn(self.actionC_Header_File_h,QtCore.SIGNAL("activated()"),self.newCHeaderFile)
        conn(self.actionFortran,QtCore.SIGNAL("activated()"),self.newFortranFile)
        conn(self.actionPython_File,QtCore.SIGNAL("activated()"),lambda x="py":self.template(x))
        conn(self.actionC,QtCore.SIGNAL("activated()"),lambda x="cpp":self.template(x))
        conn(self.actionFortran,QtCore.SIGNAL("activated()"),lambda x="f":self.template(x))


        QtCore.QMetaObject.connectSlotsByName(py_de)


	    ####################################
        ## Method for creating a tab
        ####################################

    def createTab(self, py_de, ext, filename=""):
        newTabName = "tab" + str(self.centralwidget.count())
        newTextEditName = "textEdit" + str(self.centralwidget.count())
        print "createTab(): creating tab %s" % (newTabName)
        self.tab = QtGui.QWidget()
        self.tab.setObjectName(newTabName)
        self.tablayout = QtGui.QGridLayout(self.tab)
        self.centralwidget.addTab(self.tab,"")
        newTabIndex = self.centralwidget.indexOf(self.tab)
        if filename == "":
            filename = "Untitled" + str((newTabIndex + 1))
        newTabTitle = str(filename) + str(ext)
        self.centralwidget.setCurrentIndex(self.centralwidget.indexOf(self.tab))
        self.centralwidget.setTabText(newTabIndex, QtGui.QApplication.translate("py_de", newTabTitle, None, QtGui.QApplication.UnicodeUTF8))
        self.textEdit = QsciScintilla(self.tab)
        self.textEdit.setFont(self.font)
        self.textEdit.setMarginsFont(self.font)
        self.textEdit.setMarginWidth(0, self.fm.width( "00000" ) + 5)
        self.textEdit.setMarginLineNumbers(0, True)
        self.textEdit.setEdgeMode(QsciScintilla.EdgeLine)
        self.textEdit.setEdgeColumn(80)
        self.textEdit.setEdgeColor(QtGui.QColor("#FF0000"))
        self.textEdit.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.textEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        self.textEdit.setCaretLineVisible(True)
        self.textEdit.setCaretLineBackgroundColor(QtGui.QColor("#CDA869"))
        self.textEdit.setMarginsBackgroundColor(QtGui.QColor("#333333"))
        self.textEdit.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))
        self.textEdit.setFoldMarginColors(QtGui.QColor("#99CC66"),QtGui.QColor("#333300"))
        lexer = QsciLexerPython()
        lexer.setDefaultFont(self.font)
        self.textEdit.setLexer(lexer)
        self.textEdit.show()
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(1),QtGui.QSizePolicy.Policy(1))
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.textEdit.sizePolicy().hasHeightForWidth())
        self.textEdit.setSizePolicy(sizePolicy)
        self.textEdit.setObjectName(newTextEditName)
        self.tablayout.addWidget(self.textEdit, 0, 0, 1, 1)


	#####################################
	## Functions for menu button actions
	#####################################

    def openFile(self):
        fileName = QFileDialog.getOpenFileName()
        print fileName
        index = fileName.lastIndexOf("/")
        newFileName = fileName[index+1:]
        print newFileName
        self.createTab(py_de, "", newFileName)
        self.textEdit.setText(open(fileName).read())

    def printFile(self): # Needs some work...
        printDialog = QPrintDialog(self.printer, py_de)
        if printDialog.exec_() == QDialog.Accepted:
            margin = 10
            pageNum = 1
            yPos = 0
            printJob = QPainter()
            printJob.begin(self.printer)
            printJob.setFont(self.font)
            fm = printJob.fontMetrics()

            for i in range(self.textEdit.lines()):
                if margin + yPos > self.printer.height() - margin:
                    pageNum += 1
                    self.printer.newPage()
                    yPos = 0
                printJob.drawText(margin,               # X
                                  margin + yPos,        # Y
                                  self.printer.width(), # Width
                                  self.printer.height(),# Height
                                  QtCore.Qt.AlignTop,       # Alignment
                                  self.textEdit.text(i - 1)# The text to print
                                  )
                yPos += fm.lineSpacing()
            printJob.end

    def saveFile(self):
        fileName = QFileDialog.getSaveFileName()
        f = open(fileName, "w")
        f.write(self.textEdit.text())

    def saveAsFile(self):
        QKeySequence(self.textEdit.trUtf8("Ctrl+Shft+S", "File|Save As"))
        fileName = QFileDialog.getSaveFileName()
        f = open(fileName, "w")
        f.write(self.textEdit.text())

    def goToLine(self):
        maxLine = str(self.textEdit.lines())
        newLineNumber, ok = QInputDialog.getInteger(self.centralwidget,
                                                    "Go to line",
                                                    "Line number: (1, " + maxLine+")")
        if ok:
            newLineNumber -= 1  # Convert from 1-based to 0-based
            self.textEdit.ensureLineVisible(newLineNumber)
            self.textEdit.setCursorPosition(newLineNumber, 0)
            # TODO: Find docs on qscintilla's gotoline(int)


    def cut(self):
        QKeySequence(self.textEdit.trUtf8("Ctrl+X", "Edit|Cut"))

    def copy(self):
        QKeySequence(self.textEdit.trUtf8("Ctrl+C", "Edit|Copy"))

    def paste(self):
        QKeySequence(self.textEdit.trUtf8("Ctrl+V", "Edit|Paste"))

    def find(self):
        QKeySequence(self.textEdit.trUtf8("Ctrl+F", "Edit|Find"))

    def newPythonFile(self):
        ext = ".py"
        self.createTab(py_de, ext)

    def newCFile(self):
        ext = ".cpp"
        self.createTab(py_de, ext)

    def newCHeaderFile(self):
        ext = ".h"
        self.createTab(py_de, ext)

    def newFortranFile(self):
        ext = ".f"
        self.createTab(py_de, ext)

    def closeTab(self):
        self.centralwidget.removeTab(self.centralwidget.currentIndex())


	    ##################################
        ## Function for adding actions to
	    ## various menu items.
        ##################################

    # Generates python code to create menu items then execs it
    # Should never be passed any input from a user or a file.
    def initAction(self, actionName, menus = None, shortCutKeys = None, iconFileName = None):
        assert actionName[0:6] == "action"
        commands = list()
        commands.append("self." + actionName + "=QtGui.QAction(py_de)")
        if shortCutKeys:
            commands.append("self." + actionName + ".setShortcut('" + shortCutKeys + "')")
        if iconFileName:
           commands.append("self." + actionName + ".setIcon(QtGui.QIcon('" + self.imagesDir + iconFileName + "'))")
        commands.append("self." + actionName + ".setObjectName('" + actionName + "')" )
        if menus:
            assert type(menus) == type(()) or type(menus) == type("string")
            if type(menus) == type("string"): # Add action to only one menu
                commands.append("self." + menus + ".addAction(self." + actionName + ")")
            else: # Menus is a tuple of menus on which to add this action
                for menu in menus:
                    commands.append("self." + menu + ".addAction(self." + actionName + ")")
        for command in commands:
            exec(command, globals(), locals())

    def createActions(self, py_de):
        self.menuFile.addAction(self.menuNew.menuAction())
        self.initAction("actionCopy","menuEdit", "Ctrl+C", "edit-copy.png")
        self.initAction("actionCut", "menuEdit", "Ctrl+X", "edit-cut.png")
        self.initAction("actionPaste", "menuEdit", "Ctrl+V", "edit-paste.png")
        self.initAction("actionSelect_All", "menuEdit", "Ctrl+A", "edit-select-all.png")
        self.initAction("actionFind", "menuEdit", "Ctrl+F", "edit-find.png")
        self.initAction("actionReplace", "menuEdit", "Ctrl+H")
        self.initAction("actionGoToLine", "menuEdit", "Ctrl+G")
        self.initAction("actionOpen", "menuFile", "Ctrl+O", "document-open.png")
        self.initAction("actionSave", "menuFile", "Ctrl+S", "document-save.png")
        self.initAction("actionSave_As", "menuFile", "Ctrl+Shift+S", "document-save-as.png")
        self.initAction("actionPrint", "menuFile", "Ctrl+P", "document-print.png")
        self.initAction("actionClose", "menuFile", "Ctrl+W", "dialog-close.png")
        self.initAction("actionQuit", "menuFile", None, "application-exit.png")
        self.initAction("actionBuild", "menuBuild", "F7", "run-build-file.png")
        self.initAction("actionBuild_All", "menuBuild", "Ctrl+Alt+F7", "run-build.png")
        self.initAction("actionRun", "menuBuild", "F5", "arrow-right.png")
        self.initAction("actionClean", "menuBuild", "Ctrl+Shift+C", "edit-clear.png")
        self.initAction("actionAbout", "menuHelp", None, "help-about.png")
        self.initAction("actionSelect_Language", None, None, None)
        self.initAction("actionFortran", "menuNew", None, "file-fortran.png")
        self.initAction("actionC", "menuNew", None, "file-cpp.png")
        self.initAction("actionPython_File", "menuNew", "file-python.png")
        self.initAction("actionC_Header_File_h", "menuNew", None, "file-header.png")
        self.initAction("actionNewTemplate", ("menuNew", "menuTools"), None, "document-new.png")

        self.menuNew.setIcon(QtGui.QIcon(self.imagesDir + "document-new.png"))
        self.menuTools.addAction(self.menuFormat.menuAction())

        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuEdit.menuAction())
        self.menubar.addAction(self.menuBuild.menuAction())
        self.menubar.addAction(self.menuTools.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())

	    ####################################
        ## Method for creating a toolbar
        ####################################

    def createToolBar(self, py_de):
        self.toolBar = QtGui.QToolBar(py_de)
        self.toolBar.setObjectName("toolBar")
        py_de.addToolBar(QtCore.Qt.TopToolBarArea,self.toolBar)

        self.toolBar.addAction(self.actionBuild)


	    ####################################
        ## Method for creating menus
        ####################################

    def createMenus(self, py_de):
        self.menubar = QtGui.QMenuBar(py_de)
        self.menubar.setGeometry(QtCore.QRect(0,0,502,26))
        self.menubar.setObjectName("menubar")

        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")

        self.menuNew = QtGui.QMenu(self.menuFile)
        self.menuNew.setObjectName("menuNew")

        self.menuEdit = QtGui.QMenu(self.menubar)
        self.menuEdit.setObjectName("menuEdit")

        self.menuBuild = QtGui.QMenu(self.menubar)
        self.menuBuild.setObjectName("menuBuild")

        self.menuTools = QtGui.QMenu(self.menubar)
        self.menuTools.setObjectName("menuTools")

        self.menuFormat = QtGui.QMenu(self.menuTools)
        self.menuFormat.setObjectName("menuFormat")

        self.menuHelp = QtGui.QMenu(self.menubar)
        self.menuHelp.setObjectName("menuHelp")
        py_de.setMenuBar(self.menubar)

    def retranslateUi(self, py_de):
        py_de.setWindowTitle(QtGui.QApplication.translate("py_de", "py_de", None, QtGui.QApplication.UnicodeUTF8))
        self.menuFile.setTitle(QtGui.QApplication.translate("py_de", "File", None, QtGui.QApplication.UnicodeUTF8))
        self.menuNew.setTitle(QtGui.QApplication.translate("py_de", "New", None, QtGui.QApplication.UnicodeUTF8))
        self.menuEdit.setTitle(QtGui.QApplication.translate("py_de", "Edit", None, QtGui.QApplication.UnicodeUTF8))
        self.menuBuild.setTitle(QtGui.QApplication.translate("py_de", "Build", None, QtGui.QApplication.UnicodeUTF8))
        self.menuTools.setTitle(QtGui.QApplication.translate("py_de", "Tools", None, QtGui.QApplication.UnicodeUTF8))
        self.menuFormat.setTitle(QtGui.QApplication.translate("py_de", "Format", None, QtGui.QApplication.UnicodeUTF8))
        self.menuHelp.setTitle(QtGui.QApplication.translate("py_de", "Help", None, QtGui.QApplication.UnicodeUTF8))
        self.toolBar.setWindowTitle(QtGui.QApplication.translate("py_de", "py_de", None, QtGui.QApplication.UnicodeUTF8))
        self.actionCopy.setText(QtGui.QApplication.translate("py_de", "Copy", None, QtGui.QApplication.UnicodeUTF8))
        self.actionCut.setText(QtGui.QApplication.translate("py_de", "Cut", None, QtGui.QApplication.UnicodeUTF8))
        self.actionPaste.setText(QtGui.QApplication.translate("py_de", "Paste", None, QtGui.QApplication.UnicodeUTF8))
        self.actionSelect_All.setText(QtGui.QApplication.translate("py_de", "Select All", None, QtGui.QApplication.UnicodeUTF8))
        self.actionFind.setText(QtGui.QApplication.translate("py_de", "Find", None, QtGui.QApplication.UnicodeUTF8))
        self.actionReplace.setText(QtGui.QApplication.translate("py_de", "Replace", None, QtGui.QApplication.UnicodeUTF8))
        self.actionGoToLine.setText(QtGui.QApplication.translate("py_de", "Go To Line", None, QtGui.QApplication.UnicodeUTF8))
        self.actionOpen.setText(QtGui.QApplication.translate("py_de", "Open", None, QtGui.QApplication.UnicodeUTF8))
        self.actionSave.setText(QtGui.QApplication.translate("py_de", "Save", None, QtGui.QApplication.UnicodeUTF8))
        self.actionSave_As.setText(QtGui.QApplication.translate("py_de", "Save As", None, QtGui.QApplication.UnicodeUTF8))
        self.actionPrint.setText(QtGui.QApplication.translate("py_de", "Print", None, QtGui.QApplication.UnicodeUTF8))
        self.actionClose.setText(QtGui.QApplication.translate("py_de", "Close", None, QtGui.QApplication.UnicodeUTF8))
        self.actionQuit.setText(QtGui.QApplication.translate("py_de", "Quit Py-DE", None, QtGui.QApplication.UnicodeUTF8))
        self.actionBuild.setText(QtGui.QApplication.translate("py_de", "Build", None, QtGui.QApplication.UnicodeUTF8))
        self.actionBuild_All.setText(QtGui.QApplication.translate("py_de", "Build All", None, QtGui.QApplication.UnicodeUTF8))
        self.actionRun.setText(QtGui.QApplication.translate("py_de", "Run", None, QtGui.QApplication.UnicodeUTF8))
        self.actionClean.setText(QtGui.QApplication.translate("py_de", "Clean", None, QtGui.QApplication.UnicodeUTF8))
        self.actionAbout.setText(QtGui.QApplication.translate("py_de", "About Py-DE", None, QtGui.QApplication.UnicodeUTF8))
        self.actionSelect_Language.setText(QtGui.QApplication.translate("py_de", "Select Language", None, QtGui.QApplication.UnicodeUTF8))
        self.actionFortran.setText(QtGui.QApplication.translate("py_de", "Fortran File (.f)", None, QtGui.QApplication.UnicodeUTF8))
        self.actionC.setText(QtGui.QApplication.translate("py_de", "C++ Implementation File (.cpp)", None, QtGui.QApplication.UnicodeUTF8))
        self.actionPython_File.setText(QtGui.QApplication.translate("py_de", "Python File (.py)", None, QtGui.QApplication.UnicodeUTF8))
        self.actionC_Header_File_h.setText(QtGui.QApplication.translate("py_de", "C++ Header File (.h)", None, QtGui.QApplication.UnicodeUTF8))
        self.centralwidget.setTabText(self.centralwidget.indexOf(self.tab), QtGui.QApplication.translate("py_de", "Untitled 1", None, QtGui.QApplication.UnicodeUTF8))
        self.actionNewTemplate.setText(QtGui.QApplication.translate("py_de", "Add file as new template", None, QtGui.QApplication.UnicodeUTF8))

    def newTemplate(self):
      o = pydeTemplates.pydeTemplates("templates")

      listLanguage = QtCore.QStringList()
      listLanguage.append("Fortran")
      listLanguage.append("Python")
      listLanguage.append("C++")

      language, res = QtGui.QInputDialog.getItem(self.centralwidget,
           QtGui.QApplication.translate("py_de", "Language templates", None, QtGui.QApplication.UnicodeUTF8),
           QtGui.QApplication.translate("py_de", "Choose language", None, QtGui.QApplication.UnicodeUTF8),
           listLanguage)
      if res:
        templateName, res = QtGui.QInputDialog.getText(self.centralwidget,
            QtGui.QApplication.translate("py_de", "Template name", None, QtGui.QApplication.UnicodeUTF8),
            QtGui.QApplication.translate("py_de", "Template name", None, QtGui.QApplication.UnicodeUTF8))
        if res:
          lang=""
          if language == "Fortran":
            lang="f"
          elif language == "C++":
            lang="cpp"
          elif language == "Python":
            lang="py"
        o.newTemplate(self.textEdit.text(), lang, templateName)

    def template(self, language):
      # Upgrade: in tools menu, add some functionalities for templates (add/remove template...) -

      #load list of templates for language selected
      o = pydeTemplates.pydeTemplates("templates")
      templates  = QtCore.QStringList(o.getTemplatesListOf(language))
      templates.prepend("Empty")

      #display dialogbox with a listbox containing list of templates
      template, res = QtGui.QInputDialog.getItem(self.centralwidget,
           QtGui.QApplication.translate("py_de", "Language templates", None, QtGui.QApplication.UnicodeUTF8),
           QtGui.QApplication.translate("py_de", "Choose template", None, QtGui.QApplication.UnicodeUTF8),
           templates)
      if res:
        #load template in the editor
        self.textEdit.setText(o.loadTemplate(language, template))
Esempio n. 8
0
    editor.setMarginWidth(0, fm.width("00000") + 5)
    editor.setMarginLineNumbers(0, True)

    ## Edge Mode shows a red vetical bar at 80 chars
    editor.setEdgeMode(QsciScintilla.EdgeLine)
    editor.setEdgeColumn(80)
    editor.setEdgeColor(QtGui.QColor("#FF0000"))

    ## Folding visual : we will use boxes
    editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)

    ## Braces matching
    editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)

    ## Editing line color
    editor.setCaretLineVisible(True)
    editor.setCaretLineBackgroundColor(QtGui.QColor("#CDA869"))

    ## Margins colors
    # line numbers margin
    editor.setMarginsBackgroundColor(QtGui.QColor("#333333"))
    editor.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))

    # folding margin colors (foreground,background)
    editor.setFoldMarginColors(QtGui.QColor("#99CC66"),
                               QtGui.QColor("#333300"))

    ## Choose a lexer
    lexer = QsciLexerPython1()

    lexer.setDefaultFont(font)
Esempio n. 9
0
class editor(QtGui.QWidget):
   def __init__(self, parent, main):
       QtGui.QWidget.__init__(self)

       self.__Dir = os.path.dirname(sys.argv[0])
       self.icons =  os.path.join(self.__Dir, 'icons/')

       self.main = main

       mainLayout = QtGui.QVBoxLayout()
       mainLayout.setContentsMargins(0, 0, 0, 0)
       mainLayout.setSpacing(0)
       self.setLayout(mainLayout)

       self.editor = QsciScintilla(self)

       self.font = QtGui.QFont()
       self.font.setFamily("Consolas")
       self.font.setFixedPitch(True)
       self.font.setPointSize(10)
       self.fm = QtGui.QFontMetrics(self.font)
       self.editor.setFont(self.font)
       self.editor.setMarginsFont(self.font)
       self.editor.setMarginWidth(0, self.fm.width( "0000" ))

       self.editor.setMarginLineNumbers(0, True)
       self.editor.setUtf8(True)
       self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)
       self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)
       self.editor.setCaretLineVisible(True)
       self.editor.setCaretLineBackgroundColor(QtGui.QColor('#bfbfbf'))
       self.editor.setMarginsBackgroundColor(QtGui.QColor('#3e3e3e'))
       self.editor.setMarginsForegroundColor(QtGui.QColor('#aaff00'))
       self.editor.setFoldMarginColors(QtGui.QColor('#ff0000'),QtGui.QColor('#000000'))
       lexer = QsciLexerPython()
       self.editor.setLexer(lexer)

       fileBox = QtGui.QHBoxLayout()
       mainLayout.addLayout(fileBox, 0)

       self.saveAsButton = QtGui.QPushButton(self)
       self.saveAsButton.setText("Save As")
       self.saveAsButton.setIcon(QtGui.QIcon(self.icons+'save.png')) 
       fileBox.addWidget(self.saveAsButton)
       self.connect(self.saveAsButton, QtCore.SIGNAL("clicked()"), self.saveAs)

       self.saveButton = QtGui.QPushButton(self)
       self.saveButton.setText("Save")
       self.saveButton.setIcon(QtGui.QIcon(self.icons+'save.png')) 
       fileBox.addWidget(self.saveButton)
       self.connect(self.saveButton, QtCore.SIGNAL("clicked()"), self.save)

       self.openButton = QtGui.QPushButton(self)
       self.openButton.setText("Open") 
       self.openButton.setIcon(QtGui.QIcon(self.icons+'open.png')) 
       fileBox.addWidget(self.openButton)
       self.connect(self.openButton, QtCore.SIGNAL("clicked()"), self.openFile)

       mainLayout.addWidget(self.editor, 200)

       self.CurrentfileName = ''

   def openFile(self):
      self.fn = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home', '')
      if self.fn.isEmpty():
          return
      self.fileName = str(self.fn)
      try:
          self.f = open(self.fileName,'r').read()
          self.editor.setText(self.f)
      except:
          return
      self.CurrentfileName = self.fileName

   def openArg(self, fileName):
      self.f = open(self.fileName,'r').read()
      self.editor.setText(self.f)

   def saveAs(self):
      self.fn = QtGui.QFileDialog.getSaveFileName(self, 'Save File', '')
      try:
          self.f = open(str(self.fn),'w+r')
      except:
          return
      self.f.write(str(self.editor.text()))
      self.f.close()

   def getTitle(self):
      return self.CurrentfileName

   def save(self):
      try:
          self.f = open(self.CurrentfileName,'w+r')
      except:
          return
      self.f.write(str(self.editor.text()))
      self.f.close()

   def closeEvent(self, event):
      if (self.editor.isModified() == True):
          if (self.filename == ""):
              ret = QtGui.QMessageBox.warning(self, "PyTe",
                          "The Code has been modified.\n"
                          "Do you want to save your changes?",
                          QtGui.QMessageBox.Save | QtGui.QMessageBox.Discard |
                          QtGui.QMessageBox.Cancel)
              if ret == QtGui.QMessageBox.Save:
                  self.fn = QtGui.QFileDialog.getSaveFileName(self, 'Save File', '')
                  try:
                     self.f = open(str(self.fn),'w+r')
                  except:
                     return
                  self.f.write(str(self.text()))
                  self.f.close()
                  event.accept()
              elif ret == QtGui.QMessageBox.Cancel:
                  event.ignore()
      else:
          try:
              self.f = open(self.CurrentfileName,'w+r')
          except:
              return
          self.f.write(str(self.text()))
          self.f.close()
          event.accept()