Pergunta

I'm making a text editor with PyQt and want to have a button that indents a selected region in the QTextEdit.

I've gotten to this signal slot function:

    def Indent(self):
        tab = "    "

        cursor = QtGui.QTextCursor()

        start = cursor.selectionStart()
        end = cursor.selectionEnd()

        cursor.setPosition(end)
        cursor.movePosition(cursor.EndOfLine)
        end = cursor.position()

        cursor.setPosition(start)
        cursor.movePosition(cursor.StartOfLine)
        start = cursor.position()

        while cursor.position() < end and cursor.movePosition(cursor.Down):
            cursor.movePosition(cursor.StartOfLine)
            cursor.insertText(tab)
            end += tab.count()
            cursor.movePosition(cursor.EndOfLine)

But nothing happens when I press the button. Either I'm missing something about connecting these QTextCursor actions to the QTextEdit or this is just not the way to do it.

Does anybody know how to best indent a selected region? Thanks a lot.

Foi útil?

Solução

I think I got it working for you, but I do not understand end += tab.count.

import sys
from PyQt4 import QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        self.button = QtGui.QPushButton('Test')
        self.edit = QtGui.QTextEdit()
        layout.addWidget(self.edit)
        layout.addWidget(self.button)
        self.button.clicked.connect(self.handleTest)

    def handleTest(self):
        tab = "\t"
        cursor = self.edit.textCursor()

        start = cursor.selectionStart()
        end = cursor.selectionEnd()

        cursor.setPosition(end)
        cursor.movePosition(cursor.EndOfLine)
        end = cursor.position()

        cursor.setPosition(start)
        cursor.movePosition(cursor.StartOfLine)
        start = cursor.position()
        print cursor.position(), end

        while cursor.position() < end:
            cursor.movePosition(cursor.StartOfLine)
            cursor.insertText(tab)
            end += tab.count()
            cursor.movePosition(cursor.EndOfLine)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top