当前位置: 首页>>代码示例>>Python>>正文


Python QTextEdit.toPlainText方法代码示例

本文整理汇总了Python中PySide.QtGui.QTextEdit.toPlainText方法的典型用法代码示例。如果您正苦于以下问题:Python QTextEdit.toPlainText方法的具体用法?Python QTextEdit.toPlainText怎么用?Python QTextEdit.toPlainText使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PySide.QtGui.QTextEdit的用法示例。


在下文中一共展示了QTextEdit.toPlainText方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: AddDialogWidget

# 需要导入模块: from PySide.QtGui import QTextEdit [as 别名]
# 或者: from PySide.QtGui.QTextEdit import toPlainText [as 别名]
class AddDialogWidget(QDialog):
    """ A dialog to add a new address to the addressbook. """

    def __init__(self, parent=None):
        super(AddDialogWidget, self).__init__(parent)

        nameLabel = QLabel("Name")
        addressLabel = QLabel("Address")
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | 
                                      QDialogButtonBox.Cancel)

        self.nameText = QLineEdit()
        self.addressText = QTextEdit()

        grid = QGridLayout()
        grid.setColumnStretch(1, 2)
        grid.addWidget(nameLabel, 0, 0)
        grid.addWidget(self.nameText, 0, 1)
        grid.addWidget(addressLabel, 1, 0, Qt.AlignLeft | Qt.AlignTop)
        grid.addWidget(self.addressText, 1, 1, Qt.AlignLeft)

        layout = QVBoxLayout()
        layout.addLayout(grid)
        layout.addWidget(buttonBox)

        self.setLayout(layout)

        self.setWindowTitle("Add a Contact")

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

    # These properties make using this dialog a little cleaner. It's much 
    # nicer to type "addDialog.address" to retrieve the address as compared 
    # to "addDialog.addressText.toPlainText()"
    @property
    def name(self):
        return self.nameText.text()

    @property
    def address(self):
        return self.addressText.toPlainText()
开发者ID:Copper-64,项目名称:Examples,代码行数:44,代码来源:adddialogwidget.py

示例2: Prozor

# 需要导入模块: from PySide.QtGui import QTextEdit [as 别名]
# 或者: from PySide.QtGui.QTextEdit import toPlainText [as 别名]
class Prozor(QWidget):
    def __init__(self,element):
        #kreiramo prozor
        QWidget.__init__(self)
        self.element = element
        #iskljucujemo polja za uvecanje i minimizaciju
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowMaximizeButtonHint & ~Qt.WindowMinimizeButtonHint)
        #Podesavamo naslov
        self.setWindowTitle(self.element.ime)
        self.focusWidget()
        #editor teksta
        self.textEditor = QTextEdit()
        self.textEditor.setText(self.element.data)
        #dodajemo dugmad za primenu i odbacivanje promena
        #i povezujemo ih sa odgovarajucim funkcijama
        self.dugmeOk = QPushButton("Potvrdi")
        self.dugmeOtkazi = QPushButton("Otkazi")
        self.connect(self.dugmeOk,SIGNAL('clicked()'),self,SLOT('podesi()'))
        self.connect(self.dugmeOtkazi,SIGNAL('clicked()'),self,SLOT('zatvori()'))
        #formiramo raspored
        raspored = QFormLayout()
        raspored.addRow(self.textEditor)
        raspored.addRow(self.dugmeOtkazi,self.dugmeOk)
        self.setLayout(raspored)
        
    def zatvori(self):
        '''
            Funkcija za dugme otkazi promene, vraca parametre liste na trenutno stanje aplikacije
        '''
        self.textEditor.clear()
        self.textEditor.setText(self.element.data)
        self.hide()
        
    def podesi(self):
        '''
            Funkcija za dugme potvrdi promene, poziva akcije za izmenu jezika i izgleda
        '''
        self.element.data = self.textEditor.toPlainText()
        self.hide()
        
    def closeEvent(self, event):
        self.zatvori()
开发者ID:satishgoda,项目名称:SimulationZ,代码行数:44,代码来源:Prozor.py

示例3: ToolBox

# 需要导入模块: from PySide.QtGui import QTextEdit [as 别名]
# 或者: from PySide.QtGui.QTextEdit import toPlainText [as 别名]

#.........这里部分代码省略.........
            self.buttonCapture.setText('Capture')
        if const.STATE_INTERACTIVE_RESET == state:
            self.buttonCapture.setEnabled(True)
            self.buttonCapture.setText('Capture')
        elif const.STATE_INTERACTIVE_ACTIVE == state:
            self.buttonCapture.setEnabled(True)
            self.buttonCapture.setText('Capture')

    def setMessageInfo(self,info):
        self.msgInfo.setText(info)

    def setAvailable(self,threads):
        self.sig.emit(threads)

    def toggleThreadDisplay(self,item):
        print(self.listThread.currentRow())
        #if item.isSelected():
        #    print(item.text() + "  is selected")
        #else:
        #    print(item.text() + "  is not selected")
        self.diagramView.showThread(self.listThread.currentRow(),item.isSelected())

    def hideAllMsgNamedAsSelected(self):
        self.diagramView.hideAllMessageSelected()

    def addThreadList(self,threads):

        if not self.groupBoxThreadInfo:
            self.groupBoxThreadInfo = QGroupBox()
            self.threadInfo = QLabel("Thread Info.")
            self.groupBoxThreadInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;")

        if not self.threadvbox:
            self.threadvbox = QVBoxLayout()

        if not self.listThread:
            self.listThread = QListWidget()
            
        self.listThread.setFixedWidth(200)
        self.listThread.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
        QtCore.QObject.connect(self.listThread, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.toggleThreadDisplay)
        self.threadvbox.addWidget(self.threadInfo)
        self.threadvbox.addWidget(self.listThread)
        self.groupBoxThreadInfo.setLayout(self.threadvbox)
        self.addWidget(self.groupBoxThreadInfo)
        self.groupBoxThreadInfo.setSizePolicy(self.sizePolicy)

        for id in threads:
            item = QtGui.QListWidgetItem(id)
            self.listThread.addItem(item)

    def connectController(self,controller):
        self.controller = controller
        self.connect(controller,QtCore.SIGNAL('setAvailable()'),self.setAvailable)
       
    def connectDiagramView(self,view):
        self.diagramView = view
 
    def disconnectMsgRcv(self,receiver):
        print("Implement this method !!! disconnectMsgRcv")

    def connectMsgRcv(self,receiver):
        self.msgRcv.append(receiver)

    def notifyHide(self):
        for rcv in self.msgRcv:
            rcv.activateHide(True)

    def showHiddenLifelines(self):
        response, selected_items = HiddenDialog.HiddenDialog.getSelectedItems(self.diagramView.getHiddenLifeLines())
        if response:
            self.diagramView.showLifelines(selected_items)

    def showHiddenMessages(self):
        response, selected_items = HiddenMessageDialog.HiddenMessageDialog.getSelectedItems(self.diagramView.getHiddenMessages(),self.diagramView.getHiddenLifeLines())
        if response:
            if selected_items[3] in self.diagramView.getHiddenLifeLines():
                confirmation = ShowLifeLineDialog.ShowLifeLineDialog.confirmToShowLifeLine(selected_items[3])
                if confirmation:
                    self.diagramView.showLifelines([selected_items[3]])
                    self.diagramView.showMessages(selected_items)
            else:
                self.diagramView.showMessages(selected_items)

    def notifyCapture(self):
        for rcv in self.msgRcv:
            rcv.activateCapture(True)
    
    def moveToPrev(self):
        for rcv in self.msgRcv:
            rcv.moveToPrev()
        
    def moveToNext(self):
        for rcv in self.msgRcv:
            rcv.moveToNext()

    def searchMsg(self):
        str = self.editTextSearch.toPlainText()
        for rcv in self.msgRcv:
            rcv.searchMessage(str)
开发者ID:OpenDanbi,项目名称:Sherlock,代码行数:104,代码来源:ToolBox.py

示例4: App

# 需要导入模块: from PySide.QtGui import QTextEdit [as 别名]
# 或者: from PySide.QtGui.QTextEdit import toPlainText [as 别名]
class App(QMainWindow):

    def __init__(self, parent=None):
        """Create Qt widgets, connect event handlers."""

        super(App, self).__init__(parent)
        
        self.windowTitle = 'DMD | '
        self.fileName = ''
        
        self.setWindowTitle(self.windowTitle + 'Unsaved File')
        
        exitAction = QAction('Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)
        
        openAction = QAction('Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open Markdown File')
        openAction.triggered.connect(self.openFile)
        
        newAction = QAction('New', self)
        newAction.setShortcut('Ctrl+N')
        newAction.setStatusTip('New Markdown File')
        newAction.triggered.connect(self.newFile)

        saveAction = QAction('Save', self)
        saveAction.setShortcut('Ctrl+S')
        saveAction.setStatusTip('Save File')
        saveAction.triggered.connect(self.saveFile)
        
        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        
        fileMenu.addAction(newAction)
        fileMenu.addAction(openAction)
        fileMenu.addAction(saveAction)
        fileMenu.addAction(exitAction)

        self.setGeometry(300, 300, 1024, 768)
        
        self.show()

        self.txtInput = QTextEdit()
        self.txtInput.setTabStopWidth(20)
        self.webPreview = QWebView()
        self.webPreview.setHtml('Start typing...', baseUrl=QUrl('preview'))
        
        self.txtInput.textChanged.connect(self.loadPreview)
        
        splitter = QSplitter()
        splitter.addWidget(self.txtInput)
        splitter.addWidget(self.webPreview)


        self.setCentralWidget(splitter)
        

    def loadPreview(self):
        """Set the QWebView to the value of the parsed document."""
    
        html = markdown2.markdown(self.txtInput.toPlainText())
        self.webPreview.setHtml(html, baseUrl=QUrl('preview'))
        

    def openFile(self):
        """Handles opening a file, just like any other text editor."""
    
        self.fileName = QFileDialog.getOpenFileName()[0]
    
        fh = open(self.fileName, 'r')
        
        contents = fh.read()
        
        fh.close()
    
        self.txtInput.setText(contents)
        self.setWindowTitle(self.windowTitle + self.fileName)
       

    def newFile(self):
        """Creates a new file, just like any other text editor."""
           
        self.fileName = ''
        self.setWindowTitle(self.windowTitle + 'Unsaved File')
        self.txtInput.setText('')
        
        
    def saveFile(self):
        """Saves the file, just like any other text editor."""
    
        if not self.fileName == '':
            fh = open(self.fileName, 'w')
            fh.write(self.txtInput.toPlainText())
            fh.close()
            self.setWindowTitle(self.windowTitle + self.fileName)
            
#.........这里部分代码省略.........
开发者ID:lastkarrde,项目名称:deskmarkdown,代码行数:103,代码来源:deskmarkdown.py

示例5: addSignal

# 需要导入模块: from PySide.QtGui import QTextEdit [as 别名]
# 或者: from PySide.QtGui.QTextEdit import toPlainText [as 别名]
class addSignal():
    def __init__(self, parent):
        
        self.parent = parent
        
        self.dialog = QDialog(self.parent.parent)
        
        mainLayout = QVBoxLayout()
        
        aux = QHBoxLayout()
        name = QLabel("Signal Name: ")
        self.nameBox = QLineEdit()
        aux.addWidget(name)
        aux.addWidget(self.nameBox)
        aux2 = QWidget()
        aux2.setLayout(aux)
        mainLayout.addWidget(aux2)   
        
                                       
        auxBox = QHBoxLayout()
        self.fileLabel = QLabel("File: ")
        button = QPushButton("...")
        button.clicked.connect(self.fileChoosing)
        auxBox.addWidget(self.fileLabel)
        auxBox.addWidget(button)
        auxWidget = QWidget()
        auxWidget.setLayout(auxBox)
        mainLayout.addWidget(auxWidget)
        
        
        hBox = QHBoxLayout()
        hBox.addWidget(QLabel("Sample Rate (Hz): "))
        self.sampleRate = QLineEdit()
        self.sampleRate.setText("60")
        hBox.addWidget(self.sampleRate)
        auxW = QWidget()
        auxW.setLayout(hBox)
        mainLayout.addWidget(auxW)      
        
        
        auxBox = QHBoxLayout()
        commentaryLabel = QLabel("Commentary: ")
        self.commentaryBox = QTextEdit()
        auxBox.addWidget(commentaryLabel)
        auxBox.addWidget(self.commentaryBox)
        auxWidget = QWidget()
        auxWidget.setLayout(auxBox)
        mainLayout.addWidget(auxWidget)
        
        
        buttonOk = QPushButton("Add Signal")
        buttonOk.clicked.connect(self.addSignalClicked)
        mainLayout.addWidget(buttonOk)
        
        self.dialog.setLayout(mainLayout)
        self.dialog.show()
        
    def fileChoosing(self):
                        
            filePicker = QFileDialog()
            self.fileName = filePicker.getOpenFileName(self.parent, 'Select File')[0]
            filePicker.destroy() 
            self.fileLabel.setText("File: " + self.fileName)            
            filePicker.destroy()
        
    def addSignalClicked(self):
                
        if self.fileName != "" and self.nameBox.text() != "":
            self.parent.parent.project.addSignal(self.nameBox.text(), self.fileName, self.commentaryBox.toPlainText(), self.sampleRate.text())
            self.dialog.setVisible(False)
            label = self.parent.parent.project.signalList[-1][0].getImage()
            
            if self.parent.parent.table.columnCount() == 0: self.parent.parent.table.setColumnCount(1)
            
            self.parent.parent.table.setRowCount(self.parent.parent.table.rowCount() + 1)
            
            self.parent.parent.table.setCellWidget(len(self.parent.parent.project.signalList)-1,0,label)
            self.parent.parent.table.resizeColumnsToContents()
            self.parent.parent.table.resizeRowsToContents()
            self.parent.parent.setLabels()
                            
            msg = QMessageBox(self.parent.parent)
            msg.setText("Signal added")
            msg.show()       
开发者ID:antiface,项目名称:DSP-Tool,代码行数:86,代码来源:addSignal.py

示例6: SampleWindow

# 需要导入模块: from PySide.QtGui import QTextEdit [as 别名]
# 或者: from PySide.QtGui.QTextEdit import toPlainText [as 别名]

#.........这里部分代码省略.........
    self.mainToolBar.addAction(self.pasteAction)
    self.mainToolBar.addSeparator()
    self.mainToolBar.addAction(self.undoAction)
    self.mainToolBar.addAction(self.redoAction)


 def openFile(self):
    self.fileName, self.filterName =QFileDialog.getOpenFileName(self)
    try:
        self.textEdit.setText(open(self.fileName).read())
    except:
        pass
    # Slots called when the menu actions are triggered
 def newFile(self):
    self.textEdit.setText('')
 def exitFile(self):
    self.close()
 def aboutHelp(self):
    QMessageBox.about(self, "About Simple Text Editor",
    "This example demonstrates the use "
    "of Menu Bar")

 def fontChange(self):
    (font, ok) = QFontDialog.getFont(QFont("Helvetica [Cronyx]", 10), self)
    if ok:
        self.textEdit.setCurrentFont(font)

 def saveFile(self):
    if self.fileName == None or self.fileName == '':
        self.fileName, self.filterName = QFileDialog.getSaveFileName(self, \
        filter=self.filters)
    if(self.fileName != ''):
        file = open(self.fileName, 'w')
        file.write(self.textEdit.toPlainText())
        self.statusBar().showMessage("File saved", 2000)
 def image_ss(self):
    from PySide import QtGui, QtCore

    import wxpython_flash_Simple_working
    hbox = QtGui.QHBoxLayout(self)
    pixmap = QtGui.QPixmap('C:\Users\Hamed\Pictures\LED\led.jpg')

    lbl = QtGui.QLabel(self)
    lbl.setPixmap(pixmap)

    hbox.addWidget(lbl)
    self.setLayout(hbox)

    self.setGeometry(300, 300, 280, 170)
    self.setWindowTitle('Red Rock')

    self.show()


    # from PIL import Image
    # from PySide.QtGui import QImage, QImageReader, QLabel, QPixmap, QApplication
    #
    # im = Image.open('C:\Users\Hamed\Documents\soheil sites image\imageedit__9411602959.gif')
    # data = im.tostring('raw')
    #
    ##app = QApplication([])
    ## image = QImage(data);
    # image = QImage(data, im.size[0], im.size[1], QImage.Format_ARGB32)
    # pix = QPixmap.fromImage(image)
    # lbl = QLabel()
    # lbl.setPixmap(pix)
开发者ID:Heroku-elasa,项目名称:heroku-buildpack-python-ieee-new,代码行数:70,代码来源:pyside-menu.py

示例7: MainWindow

# 需要导入模块: from PySide.QtGui import QTextEdit [as 别名]
# 或者: from PySide.QtGui.QTextEdit import toPlainText [as 别名]

#.........这里部分代码省略.........
        edit.addAction(a['edit-copy'])
        edit.addAction(a['edit-paste'])

        tools = self.addToolBar("Tools")
        tools.setObjectName('toolsbar')
        tools.addAction(a['addon-manager'])
        tools.addAction(a['view-refresh'])

    ##### Statusbars! #########################################################

    def init_statusbar(self):
        self.statusBar().showMessage("Ready.")

    ##### Settings! ###########################################################

    def init_settings(self):
        self.restoreGeometry(profile.get("geometry"))
        self.restoreState(profile.get("state"))

    def save_settings(self):
        profile.set("geometry", self.saveGeometry())
        profile.set("state", self.saveState())

    ##### Actual Actions! #####################################################

    def update_title(self):
        if self.current_file:
            title = os.path.basename(self.current_file)
        else:
            title = "Untitled"
        self.setWindowTitle("%s - %s" % (title,
                QApplication.instance().applicationName()))

    def action_new(self):
        if self.try_save():
            self.editor.clear()
            self.current_file = None
            self.update_title()

    def action_open(self):
        if self.try_save():
            fn = QFileDialog.getOpenFileName(self)[0]
            if not fn:
                return

            self.do_open(fn)

    def do_open(self, fn):
        with open(fn, 'r') as f:
            content = f.read()

        self.editor.setPlainText(content)
        self.current_file = fn
        self.update_title()

    def action_save(self):
        if not self.editor.document().isModified():
            return

        if not self.current_file:
            self.current_file = QFileDialog.getSaveFileName(self)[0]
            self.update_title()

        if not self.current_file:
            return

        with open(self.current_file, 'w') as f:
            f.write(self.editor.toPlainText())
        self.editor.document().setModified(False)

    ##### Adventure! ##########################################################

    def try_save(self):
        if self.editor.document().isModified():
            ret = QMessageBox.warning(self, "Blah Blah Blah",
                    "That's an awfully nice modified document you've got there"
                    ". It'd be a shame if anything... happened to it. Catch "
                    "my drift?",
                    QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel
                    )
            if ret == QMessageBox.Save:
                self.action_save()

            elif ret == QMessageBox.Cancel:
                return False

        return True

    def closeEvent(self, event):
        if self.try_save():
            self.save_settings()

            if self in self.windows:
                self.windows.remove(self)

            plugins.run_signal('close_window', self)

            event.accept()
        else:
            event.ignore()
开发者ID:apt-shansen,项目名称:siding,代码行数:104,代码来源:main_window.py

示例8: Ui_MainWindow

# 需要导入模块: from PySide.QtGui import QTextEdit [as 别名]
# 或者: from PySide.QtGui.QTextEdit import toPlainText [as 别名]

#.........这里部分代码省略.........
        fname, _ = QFileDialog.getOpenFileName(self, u'Ouvrir')
        self.occ = {}
        self.hCodes = {}
        self.aCodes = {}
        self.hCost = {}
        self.aCost = {}
        self.hCodes = create_dict_from_file(fname)
        self.update_codes_table()
        self.logLab.setText(u"Dictionnaire de Huffman importé.")
        return self.hCodes

    def save_dict(self):
        """Enregistrer le dictionnaire de codes Huffman."""
        fname, _ = QFileDialog.getSaveFileName(self, "Enregistrer sous")
        save_dict_to_file(fname, self.hCodes)

    def make_tab_rows(self):
        """Génère le remplissage des lignes du tableau des codes."""
        dictList = [self.occ, self.aCodes, self.hCodes, self.aCost, self.hCost]
        tabList = []
        charList = self.hCodes.keys() if self.hCodes else self.occ.keys()
        for char in charList:
            l = ["'" + char + "'"]
            for dic in dictList:
                try:
                    l.append(dic[char])
                except KeyError:
                    l.append('')
            tabList.append(l)
        return tabList

    def encode_text(self, wizard=True):
        """Encode le texte original."""
        self.text = self.orgText.toPlainText().encode('utf-8')
        if not self.text:
            self.compressedText.setText(u"")
            self.asciiText.setText(u"")
            self.logLab.setText(
                u"<font color=#A52A2A>Rien à compresser.</font>")
            return
        self.occ = {}
        self.tree = ()
        self.hCodes = {}
        self.aCodes = {}
        self.hCost = {}
        self.aCost = {}
        self.hSqueezed = []
        self.aSqueezed = []
        self.stringHSqueezed = ''
        self.stringASqueezed = ''
        if wizard:
            self.launch_wizard(
                EncodeWizard(self),
                u"<font color=#008000>Compression achevée.</font>")
        else:
            self.make_occ()
            self.make_tree()
            self.make_codes()
            self.make_cost()
            self.make_encoded_text()
            self.make_comp()

    def decode_text(self, wizard=True):
        """Décode le texte compressé."""
        self.codeString = str(
            self.compressedText.toPlainText().replace(' ', ''))
开发者ID:mathieufrh,项目名称:huffmanwizard,代码行数:70,代码来源:huffgui.py

示例9: ScratchPadWidget

# 需要导入模块: from PySide.QtGui import QTextEdit [as 别名]
# 或者: from PySide.QtGui.QTextEdit import toPlainText [as 别名]
class ScratchPadWidget(QtGui.QWidget):

    def __init__(self, parent):
        """
        Constructor
        This widget is kind of different.
        It does not exactly subclass CustomWidget
        """
        QtGui.QWidget.__init__(self)
        self.name = "Scratchpad"
        self.parent = parent
        self.config = self.parent.config
        self.iconp = self.config.icons_path
        self.icon = QIcon(self.iconp + 'pencil.png')

        self._createGui()

    def _createGui(self):

        self._createScratchPadWindow()

        scratchpad_layout = QtGui.QVBoxLayout()
        save_btn = QtGui.QPushButton("Save to file", self)
        save_btn.setIcon(QIcon(self.iconp + 'save-download.png'))
        label = QtGui.QLabel("Write some notes here")

        scratchpad_layout.addWidget(label)
        scratchpad_layout.addWidget(self.scratchpad_window)
        scratchpad_layout.addWidget(save_btn)

        # Connect signals and slots
        save_btn.clicked.connect(self._saveButtonClicked)
        self.setLayout(scratchpad_layout)

    def _createScratchPadWindow(self):
        """
        Some binary analysis commands will output to this.
        """
        self.scratchpad_window = QTextEdit()
        self.scratchpad_window.setFontPointSize(9)

    #################################################################
    # GUI Callbacks
    #################################################################
    def _saveButtonClicked(self):

        try:
            filename, flt = QFileDialog.getSaveFileName(
                self,
                "File to save notes",
                "",
                selectedFilter = '*.txt')

            sp_text = self.scratchpad_window.toPlainText()

            with open(filename, 'w') as f:
                f.write(sp_text)

            print "Saved notes to \"%s\"" % filename

        except:
            print "[!] Problem saving notes..."
            print traceback.format_exc()
开发者ID:chubbymaggie,项目名称:JARVIS,代码行数:65,代码来源:ScratchPadWidget.py

示例10: ConsoleWidget

# 需要导入模块: from PySide.QtGui import QTextEdit [as 别名]
# 或者: from PySide.QtGui.QTextEdit import toPlainText [as 别名]

#.........这里部分代码省略.........
    def query(self, sql):
        if not self._connection:
            self.logEdit.appendPlainText('No connection')
            return None

        try:
            query = self._connection.NewObject('Query', sql)
            result = query.Execute()
        except Exception as e:
            self.logEdit.appendPlainText(str(e))
            return None

        return result

    def refresh(self, result):
        self.model.clear()

        columns = list()
        result_columns = result.Columns
        for index in range(result_columns.Count()):
            name = result_columns.Get(index).Name
            columns.append(name)

        self.model.setColumnCount(len(columns))
        for section, name in enumerate(columns):
            self.model.setHeaderData(section, Qt.Horizontal, name)

        select = result.Choose()
        self.logEdit.appendPlainText('Selected %d records' % select.Count())
        while select.Next():
            items = list()
            for index in range(len(columns)):
                value = select.Get(index)

                item = QStandardItem('')
                if isinstance(value, bool):
                    item.setText(value and 'Yes' or 'No')

                elif isinstance(value, (int, str)):
                    item.setText(str(value))

                elif isinstance(value, datetime.datetime):
                    item.setText(value.strftime('%Y.%m.%d %H:%M:%S'))

                else:
                    item.setText(str(value))
                items.append(item)

            self.model.appendRow(items)

    @Slot()
    def executeQuery(self):
        sql = self.sqlEdit.toPlainText()
        result = self.query(sql)
        if result:
            path = os.path.join(self._home, 'last-sql.txt')
            open(path, 'w').write(sql)
            self.refresh(result)

    @Slot()
    def connectOneS(self):
        uri = self.connectionUriCombo.currentText().strip()
        if not uri:
            self.logEdit.appendPlainText('Need a connection string')
            return

        version = self.onesVersionCombo.currentText()
        comName = "V%s.COMConnector" % str(version).replace('.', '')

        pythoncom.CoInitialize()
        try:
            obj = win32com.client.Dispatch(comName)
            self._connection = obj.Connect(uri)
        except Exception as e:
            self.logEdit.appendPlainText(str(e))
            return

        self.connectAction.setDisabled(True)
        self.disconnectAction.setEnabled(True)
        self.queryAction.setEnabled(True)

        uri_history = list()
        for i in range(self.connectionUriCombo.count()):
            uri_history.append(self.connectionUriCombo.itemText(i))

        if uri not in uri_history:
            self.connectionUriCombo.clearEditText()
            self.connectionUriCombo.addItem(uri)
            self.connectionUriCombo.setCurrentIndex(len(uri_history))
            uri_history.append(uri)
            path = os.path.join(self._home, 'uri_history.txt')
            open(path, 'w').write('\n'.join(uri_history))

    @Slot()
    def disconnectOneS(self):
        pythoncom.CoUninitialize()
        self._connection = None
        self.connectAction.setEnabled(True)
        self.disconnectAction.setDisabled(True)
        self.queryAction.setDisabled(True)
开发者ID:gsfarm,项目名称:ones-console,代码行数:104,代码来源:console.py


注:本文中的PySide.QtGui.QTextEdit.toPlainText方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。